'How do I create a new series in a Pandas DataFrame and populate it with specific values?
I am new to coding in Python and seeking a little guidance using Pandas.
In brief, I would like to create a new series in a Pandas DataFrame and then populate it. I’ve recreated a simple example to illustrate my specific problem.
In my example, I am attempting to use a dictionary of car Makes (Model_Dict), and a function called Make_Calculator, to populate a new series in my DataFrame called “Make”. The function compares the car model type in the DataFrame series “Model” to a dictionary with Car-Model as the key and Car-Make as the values. The function is supposed to create, and then assign, the Car Make to a new series called “Make” in the DataFrame. When I run this, it creates a new series called “Make”, but every row was populated with “unassigned” as opposed to the actual make of the vehicle.
I am very new to Pandas, any assistance would be much appreciated.
Here is my code:
import pandas as pd
car_inventory = {'Model' : ['Versa', 'Focus', 'Outback'],
'Color' : ['Red', 'Brown', 'Green']}
car_df = pd.DataFrame(car_inventory)
Model_Dict = {'Versa': 'Nissan', 'Focus' : 'Ford', 'Outback':'Nissan'}
def Make_Calculator():
for model,make in Model_Dict.items():
for i in car_df['Model']:
if i == model:
car_df['Make'] = make
else:
car_df['Make'] = 'unassigned'
Make_Calculator()
Solution 1:[1]
If you are just looking to get information using a dictionary, I think you can find how to do this here if you are starting with pandas: Pandas Dict to Dataframe
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tylerjames |
