将系列添加到现有 DataFrame [英] Add a series to existing DataFrame
本文介绍了将系列添加到现有 DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了以下数据帧:
purchase_1 = pd.Series({'Name': 'Chris',
'Item Purchased': 'Dog Food',
'Cost': 22.50})
purchase_2 = pd.Series({'Name': 'Kevyn',
'Item Purchased': 'Kitty Litter',
'Cost': 2.50})
purchase_3 = pd.Series({'Name': 'Vinod',
'Item Purchased': 'Bird Seed',
'Cost': 5.00})
df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2'])
然后我添加了以下列:
df['Location'] = df.index
df
然后如何将以下系列添加到我的 DataFrame 中?谢谢.
How do I then add the following series to the my DataFrame? Thank you.
s = pd.Series({'Name':'Kevyn', 'Item Purchased': 'Kitty Food', 'Cost': 3.00, 'Location': 'Store 2'})
推荐答案
df = pd.concat([df, s.to_frame().T])
print (df)
Cost Item Purchased Location Name
Store 1 22.5 Dog Food Store 1 Chris
Store 1 2.5 Kitty Litter Store 1 Kevyn
Store 2 5 Bird Seed Store 2 Vinod
0 3 Kitty Food Store 2 Kevyn
也可以为默认索引添加参数 ignore_index=True
:
Also for default index is possible add parameter ignore_index=True
:
df = pd.concat([df, s.to_frame().T], ignore_index=True)
print (df)
Cost Item Purchased Location Name
0 22.5 Dog Food Store 1 Chris
1 2.5 Kitty Litter Store 1 Kevyn
2 5 Bird Seed Store 2 Vinod
3 3 Kitty Food Store 2 Kevyn
或者用loc
添加一些不在原始df
中的新索引值:
Or add some new index value which is not in original df
with loc
:
df.loc[0] = s
print (df)
Cost Item Purchased Name Location
Store 1 22.5 Dog Food Chris Store 1
Store 1 2.5 Kitty Litter Kevyn Store 1
Store 2 5.0 Bird Seed Vinod Store 2
0 3.0 Kitty Food Kevyn Store 2
因为 else 值被 Series
覆盖:
because else values are overwritten by Series
:
df.loc['Store 2'] = s
print (df)
Cost Item Purchased Name Location
Store 1 22.5 Dog Food Chris Store 1
Store 1 2.5 Kitty Litter Kevyn Store 1
Store 2 3.0 Kitty Food Kevyn Store 2 <- overwritten row
这篇关于将系列添加到现有 DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文