Generating a data set by combining various lists

Having just started with Python, I may be asking a basic question.

I have two sets of lists, one containing volume names and associated counts. Here's a sample of the data:

volumes1 = ['Shield', 'Side', 'expHall', 'Funnel', 'gridpiece']

counts1= [3911, 1479, 553, 368, 342]

and another set of lists

volumes2 = ['Shield', 'leg', 'Funnel', 'gridpiece','wafer']

counts2= [291, 469, 73, 28, 32]

It's important to note that not all volumes appear in both lists, and their order might vary.

The goal is to create a dataframe with three columns: the first column listing all volumes from both sets, the second column showing corresponding values from counts1, and the third column displaying related values from counts2.

If a volume in the first column of the dataframe isn't present in volumes1, the value in the second column is set to 0. Similarly, if a volume in the first column isn't found in volumes2, the value in the third column is set to 0. Therefore, the resulting output for the given values should look like:

| volumes | counts1 | counts2 |

| Shield | 3911 | 291 |

| Side | 1479 | 0 |

| expHall | 553 | 0 |

| Funnel | 368 | 73 |

| gridpiece | 342 | 28 |

| leg | 0 | 469 |

| wafer | 0 | 32 |

As a beginner in Python, I've struggled to achieve this elegantly and efficiently. Can anyone suggest a quick and efficient way to accomplish this?

Thanks

Answer №1

perhaps not the most efficient solution, but it works

import pandas as pd

items1 = ['Helmet', 'Gloves', 'Belt', 'Boots', 'Potion']
quantities1 = [543, 267, 98, 54, 32]
items2 = ['Helmet', 'Cape', 'Boots', 'Potion', 'Ring']
quantities2 = [156, 432, 75, 23, 56]

all_items = list(set(items1 + items2))
quantities1_adjusted = [0] * len(all_items)
quantities2_adjusted = [0] * len(all_items)

for i in range(0, len(items1)):
    index = list(all_items).index(items1[i])
    quantities1_adjusted[index] = quantities1[i]
for i in range(0, len(items2)):
    index = list(all_items).index(items2[i])
    quantities2_adjusted[index] = quantities2[i]

new_data = {
    'items': all_items,
    'quantities1': quantities1_adjusted,
    'quantities2': quantities2_adjusted
}
df = pd.DataFrame(data=new_data)
print(df)


check out https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Drag and drop a file onto the center of the screen to upload it using Python

I need to upload a file to a website using Python Selenium, but because I am working in headless mode, I cannot click on the upload file button. Is there a way for me to automatically upload a file by dropping it in the center of the screen? I attempted th ...

Discover the secret to determining 95% confidence intervals through the innovative Bootstrap approach

Currently, I am working on determining the confidence interval for the mean value through the bootstrap method in Python. To elaborate, let's assume I have a vector called 'a' containing 100 entries, and my objective is to compute the averag ...

Looping through a series of rows by utilizing ws.iter_rows within the highly efficient openpyxl reader

I am currently faced with the task of reading an xlsx file that contains 10 by 5324 cells. This is essentially what I was attempting to achieve: from openpyxl import load_workbook filename = 'file_path' wb = load_workbook(filename) ws = wb.get ...

The issue of time inconsistency in model object save when using datetime.now() in Django

This table shows my admin interface with records ordered by their id in descending order (latest record at top). Below is the code snippet used for creating model objects and saving them: notification = Notification(from_user=from_user, to_user=to_user, ...

Is there a method to calculate the total of sequential identical items within a list?

I need help finding a more efficient way to calculate the sum of consecutive similar items in a list. My current code is not producing the expected last result. Any suggestions? [Code] lst=['+1', '-1', '-1', '-1', & ...

Accessing and manipulating web elements using either XPath or CSS selectors

Having trouble selecting a specific piece of information using xpath or css selector. Error messages keep appearing. Can someone help identify the issue? This snippet is from my code: output = driver.find_element_by_xpath("//td[@class_= 'sku']" ...

Tips for executing a Python function from JavaScript, receiving input from an HTML text box

Currently, I am facing an issue with passing input from an HTML text box to a JavaScript variable. Once the input is stored in the JavaScript variable, it needs to be passed to a Python function for execution. Can someone provide assistance with this pro ...

Encountered an issue while attempting to insert a batch item into DynamoDB containing Mapvalues

I've had success using write batch items with the boto library. However, when attempting to add map values to the request, I encountered the following exception: Invalid type for parameter RequestItems.TestMap, value: {'PutRequest': ...

Trigger the execution of a Python script through a webpage with just the click of a button

I have a small web interface where I need to control a Python script that is constantly gathering data from a sensor in a while loop. Ideally, I would like the ability to start and stop this script with the click of a button. While stopping the script is s ...

Exploring the world of multi-level indexing using tuples

Working with a multi-dimensional np.array can be tricky. Knowing the shape of the first N dimensions and the last M dimensions is essential for proper indexing, as shown below: >>> n = (3,4,5) >>> m = (6,) >>> a = np.ones(n + m) ...

"Revolutionary adornment for dynamically matching regular expressions in class methods

When faced with the need to simplify method decoration, especially in situations like delegate class implementations, it can become quite cumbersome. Imagine a 3rd party "service" class with numerous methods You find yourself wanting to override many of t ...

What is the best way to turn off console messages from pywebkit?

One common issue that often arises is how to prevent the following messages from displaying on the terminal: ** Message: console message: @1: Refused to set unsafe header "cookie" ** Message: console message: @1: Refused to set unsafe header ...

Unable to assign a default value of an object variable in an object method - Python

Using Windows 10, x64, and Python 2.7.8. I'm trying to implement the code below: class TrabGraph: def __init__(self): self.radius = 1.0 def circle(self, rad=self.radius): print(rad) test = TrabGraph() test.circ ...

Storing a collection in redis-py

Attempting to save a list created from a dictionary into my redis database, I am running the following script: x = {'TLV-IST#2022-12-27~2023-01-04': '252', 'TLV-IST#2022-12-27~2023-01-17': '300'} for key, value in x ...

Acquire the website link using Selenium in the Python programming language

As a beginner in Python, I am excited to dive into web scraping and have chosen the following website as my target: Link After some research, I believe that Selenium is the best tool for the job. To get started, I wrote the code snippet below: from selen ...

A method for pinpointing the subset of numbers that shares the least amount of elements within a group of equivalent numbers

Suppose I have a dataset that is much larger, containing lists of 4 numbers selected from the range 0 to 9: (1,2,3,4) (3,5,6,0) (4,5,7,9) (1,2,7,8) If I want to identify the list(s) of numbers with the fewest matches against this collection, is there ...

Exploring Telegram chat messages with Python 3.11 and utilizing the Telethon library to retrieve them

I am seeking assistance with a Python script that uses Telethon to read messages from a chat on Telegram. Despite trying several different codes found through documentation and online resources, I have not been successful in retrieving the messages. from t ...

Fixing the sys.excepthook issue within a bash script

After creating a bash script that is successfully functioning, I am encountering the following error message: Error: close failed in file object destructor: sys.excepthook is missing lost sys.stderr Despite my efforts, I am unable to figure out how to re ...

Utilizing Bokeh for Interactive Time Series Visualization and Highlighting Specific Time Ranges

I am working on a time series plot and I want to add a layer that highlights specific ranges using glyphs. Here is an example: fig.quad(top=[10], bottom=[0], left=[0], right=[100], color="red", fill_alpha = 0.2) The user should be able to dynamically add ...

`an issue arises when attempting to run a local command using fabric2`

Take a look at the code below: from fabric2 import Connection cbis = Connection.local() with cbis.cd('/home/bussiere/Workspace/Stack/Event/'): cbis.run('git add .') Unfortunately, I encountered this error: TypeError: local() mi ...