pandas 将系列添加到现有 DataFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44156051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a series to existing DataFrame
提问by martinbshp
I created the following 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'])
I then added the following column:
然后我添加了以下列:
df['Location'] = df.index
df
How do I then add the following series to the my DataFrame? Thank you.
然后如何将以下系列添加到我的 DataFrame 中?谢谢你。
s = pd.Series({'Name':'Kevyn', 'Item Purchased': 'Kitty Food', 'Cost': 3.00, 'Location': 'Store 2'})
回答by jezrael
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
Also for default index is possible add parameter ignore_index=True
:
对于默认索引也可以添加参数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
Or add some new index value which is not in original df
with loc
:
或者增加一些新的索引值,它是不是在原来df
用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
because else values are overwritten by Series
:
因为 else 值被覆盖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
回答by Kripalu Sar
I hope it will be helpful and give you the accurate result,
我希望它会有所帮助,并为您提供准确的结果,
purchase_4 = pd.Series({'Name': 'Kevyn',
'Item Purchased': 'Kitty Food',
'Cost': 3.00,
'Location': 'Store 2'})
df2 = df.append(purchase_4, ignore_index=True)
df2.set_index(['Location', 'Name'])
回答by Jaroslav Borovsky
Solution directly from the source of your question.
直接从你的问题的来源解决。
df = df.set_index([df.index, 'Name'])
df.index.names = ['Location', 'Name']
df = df.append(pd.Series(data={'Cost': 3.00, 'Item Purchased': 'Kitty Food'}, name=('Store 2', 'Kevyn')))
df