简体   繁体   中英

Append list to dataframe (pandas)

I have a datframe that looks something like this:

id  |  item    |  amount
1   |  item_a  |  17
2   |  item_b  |  5
3   |  item_c  |  9

I also got a list with exactly the same amount of entrys like my dataframe:

list_price = [245, 189, 99]

Now I'm failing to append my list to my dataframe to create something like this:

id  |  item    |  amount  |  price
1   |  item_a  |  17      |  245
2   |  item_b  |  5       |  189
3   |  item_c  |  9       |  99

I've tried the 'lambda'-function, but it didn't work - or I'm doing it wrong??

Does anyone now the answer?

Imagine that your dataset is called df .

Then, you can use:

list_price = [245, 189, 99]
df.insert(3,"Price",list_price)
df.head()

id  |  item    |  amount  |  price
1   |  item_a  |  17      |  245
2   |  item_b  |  5       |  189
3   |  item_c  |  9       |  99

Or, alternatively, use df[price] = list_price

Hope this helps you.

import pandas as pd
data = {'item':['item_a', 'item_b', 'item_c'], 'amount':[17, 5, 9]}
df = pd.DataFrame(data)

list_price = [245, 189, 99]
df['price'] = list_price 

print(df)

[Output]:

 item amount price 0 item_a 17 245 1 item_b 5 189 2 item_c 9 99

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