Python-添加到数据框的现有行

时间:2018-09-01 16:50:12

标签: python pandas

是否可以在现有数据框中添加或减去?

例如,给出以下代码:

import pandas as pd
Apple= pd.DataFrame({'Product':['MacBook', 'iPhone', 'iPad', 'Apple Watch'],
                        'Inventory':['999', '333', '666', '190']})

是否可以将150个添加到现有库存中,以便Apple Watch的数量为340个?

3 个答案:

答案 0 :(得分:1)

使用loc和布尔选择来更新列:

Apple.loc[Apple.Product.eq('Apple Watch'), 'Inventory'] += 150

       Product  Inventory
0      MacBook        999
1       iPhone        333
2         iPad        666
3  Apple Watch        340

在您提供的示例中,Inventory包含字符串。如果实际数据相同,则需要首先强制转换为int

Apple.Inventory = Apple.Inventory.astype(int)

答案 1 :(得分:0)

首先将您的一系列字符串转换为int系列:

df['Inventory'] = df['Inventory'].astype(int)

然后您可以使用pd.DataFrame.loc

df.loc[df['Product'] == 'Apple Watch', 'Inventory'] += 150

或者,您可以将Product用作索引,然后进行更新:

df = df.set_index('Product')
df.loc['Apple Watch', 'Inventory'] += 150

使用任何一种方法,如果您有多个具有相同名称的产品,则它们的库存将每个增加150。

答案 2 :(得分:0)

如果将项目定义为int,则可以通过以下方式实现:

so How to exit Vim