Reputation: 1622
I have a dataframe df which looks like this:
CustomerId Age
1 25
2 18
3 45
4 57
5 34
I have a list called "Price" which looks like this:
Price = [123,345,1212,11,677]
I want to add that list to the dataframe. Here is my code:
df['Price'] = Price
It seems to work but when I print the dataframe the field called "Price" contains all the metadata information such as Name, Type... as well as the value of the Price.
How can I create a column called "Price" containing only the values of the Price list so that the dataframe looks like:
CustomerId Age Price
1 25 123
2 18 345
3 45 1212
4 57 11
5 34 677
Upvotes: 14
Views: 89416
Reputation: 2239
I copy pasted your example into a dataframe using pandas.read_clipboard and then added the column like this:
import pandas as pd
df = pd.read_clipboard()
Price = [123,345,1212,11,677]
df.loc[:,'Price'] = Price
df
Generating this:
CustomerId Age Price
0 1 25 123
1 2 18 345
2 3 45 1212
3 4 57 11
4 5 34 677
Upvotes: 4
Reputation: 109
import pandas as pd
df['Price'] = pd.Series(Price)
if you use this you will not get the error if you have less values in the series than to your dataframe otherwise you will get the error that will tell you have less vales in the list and that can not be appended.
Upvotes: 5
Reputation: 5437
In my Opinion, the most elegant solution is to use assign
:
df.assign(Price=Price)
CustomerId Age Price
1 25 123
2 18 345
3 45 1212
4 57 11
5 34 677
note that assign actually returns a DataFrame. Assign creates a new Column 'Price' (left Price) with the content of the list Price (right Price)
Upvotes: 25
Reputation: 1497
You can add pandas series as column.
import pandas as pd
df['Price'] = pd.Series(Price)
Upvotes: 1