将系列添加到现有DataFrame

时间:2017-05-24 10:43:07

标签: pandas

我创建了以下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中?谢谢。

s = pd.Series({'Name':'Kevyn', 'Item Purchased': 'Kitty Food', 'Cost': 3.00, 'Location': 'Store 2'})

3 个答案:

答案 0 :(得分:5)

使用concat + to_frame + T

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

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

或者使用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

因为其他值被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

答案 1 :(得分:0)

直接从您的问题来源解决。

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

答案 2 :(得分:0)

我希望它将对您有所帮助,并为您提供准确的结果,

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'])