Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list to column in Python Dataframe

Tags:

python

pandas

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
like image 972
Giampaolo Levorato Avatar asked Jul 06 '18 11:07

Giampaolo Levorato


3 Answers

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.

like image 159
akshit0106 Avatar answered Oct 23 '22 16:10

akshit0106


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
like image 27
Jorge Avatar answered Oct 23 '22 16:10

Jorge


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)

like image 37
Quickbeam2k1 Avatar answered Oct 23 '22 16:10

Quickbeam2k1