pandas – Convert list to column in Python Dataframe

pandas – Convert list to column in Python Dataframe

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

pandas – Convert list to column in Python Dataframe

You can add pandas series as column.

import pandas as pd
df[Price] = pd.Series(Price)

Leave a Reply

Your email address will not be published. Required fields are marked *