如何将Series添加到DataFrame中有自定义索引

时间:2017-04-24 14:09:45

标签: python 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 = df.set_index(['Location', 'Name'])
df2 = df.copy()
print(df2)

                Cost Item Purchased
Location Name                      
Store 1  Chris  22.5       Dog Food
         Kevyn   2.5   Kitty Litter
Store 2  Vinod   5.0      Bird Seed

然后我有以下系列:

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

当我尝试将此系列添加到我的DF时,它可以工作但是有大量的NaN:

df2 = df2.append(purchase_4, ignore_index=True)

   Cost Item Purchased Location   Name
0  22.5       Dog Food      NaN    NaN
1   2.5   Kitty Litter      NaN    NaN
2   5.0      Bird Seed      NaN    NaN
3   3.0     Kitty Food  Store 2  Kevyn

3 个答案:

答案 0 :(得分:1)

您可以使用concat

df2 = pd.concat([df2, purchase_4.to_frame().T.set_index(df.index.names)])
print (df2)
                Cost Item Purchased
Location Name                      
Store 1  Chris  22.5       Dog Food
         Kevyn   2.5   Kitty Litter
Store 2  Vinod     5      Bird Seed
         Kevyn     3     Kitty Food

loc,设置Multiindex使用()

df2.loc[(purchase_4['Location'], purchase_4['Name']),:] = purchase_4
print (df2)
                Cost Item Purchased
Location Name                      
Store 1  Chris  22.5       Dog Food
         Kevyn   2.5   Kitty Litter
Store 2  Vinod   5.0      Bird Seed
         Kevyn   3.0     Kitty Food

答案 1 :(得分:1)

替代解决方案:

In [237]: df.append(purchase_4.to_frame().T.set_index(df.index.names))
Out[237]:
                Cost Item Purchased
Location Name
Store 1  Chris  22.5       Dog Food
         Kevyn   2.5   Kitty Litter
Store 2  Vinod     5      Bird Seed
         Kevyn     3     Kitty Food

答案 2 :(得分:-2)

df = df.set_index([df.index,'Name']) df.index.names = ['位置','名称'] df = df.append(pd.Series(数据= {'成本':3.00,'购买的物品':'凯蒂食品'},名称=('商店2','凯文'))) df