简体   繁体   中英

Convert list to column in Python Dataframe

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

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)

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

You can add pandas series as column.

import pandas as pd
df['Price'] = pd.Series(Price)
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM