在python中添加嵌套列

时间:2018-02-19 19:36:06

标签: python pandas data-science pandas-groupby

我有一个pandas groupby对象,我是从一个更大的数据框中创建的,其中的数量被分组在一个人ID变量下,以及它是一个进入或离开的事务。下面是一个例子:

ID In_Out Amount
1 In 5
1 Out 8
2 In 4
2 Out 2
3 In 3
3 Out 9
4 Out 8

(抱歉,我不知道如何输入实际的样本数据)。请注意,有些人可能有一个或另一个(例如,他们可能有一些外出但没有任何进入)。

我想要的就是获得金额的差异,在这个人身下坍塌。所以理想的输出可能是字典或其他数据帧,包含每个人的数量差异,如下所示:

ID Difference
1 -3
2 2
3 -6
4 -8

我尝试了一些不同的方法来做到这一点,但我不确定如何在python中使用这些嵌套列表。

谢谢!

1 个答案:

答案 0 :(得分:1)

我们选择Out的行并将它们转换为负整数,然后使用sum()。

import pandas as pd

s = '''\
ID In_Out Amount
1  In     5
1  Out    8
2  In     4
2  Out    2
3  In     3
3  Out    9
4  Out    8'''

# Recreate dataframe
df = pd.read_csv(pd.compat.StringIO(s), sep='\s+')

# Select rows where In_Out == 'Out' and multiple by -1
df.loc[df['In_Out'] == 'Out', 'Amount'] *= -1

# Convert to dict
d = df.groupby('ID')['Amount'].sum().to_dict()
print(d)

返回:

{1: -3, 2: 2, 3: -6, 4: -8}