15

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
3
  • 5
    Please include your code, otherwise you are expecting people to guess what you wrote so that they can guess where you made an error. Commented Jul 6, 2018 at 11:55
  • 1
    What solution was the one that worked??? Commented Mar 30, 2019 at 14:58
  • 1
    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. I know this question is old, but that makes little sense. We need a minimal reproducible example or this is pointless. Commented May 1, 2020 at 16:33

4 Answers 4

25

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)

Sign up to request clarification or add additional context in comments.

Comments

5
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.

Comments

4

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

Comments

1

You can add pandas series as column.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.