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

3
我有以下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'})

当我尝试将这个系列添加到我的数据框中时,它可以工作,但会有许多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个回答

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
替代方案:
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

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

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


这太简短了,请详细说明如何解决本页顶部所描述的问题。 - Rayan Ral

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接