熊猫根据不同行中的值求和特定行

时间:2020-11-05 01:13:39

标签: pandas dataframe filter

我有一个这样的数据框。

enter image description here

这些行一次分为5行。第一组的第一行告诉我是否根据字段A包括接下来的全部4行。例如,仅由于每个行的第一行告诉我,就包括黄色,不包括蓝色。

如果部分在第一行中具有FieldA true,我想对fieldB求和。在此示例中,我想对黄色部分求和,因为该部分的第一行在fieldA中为TRUE。

我可以想到两个方法来做到这一点,但不知道如何编写代码:

  1. 如果5行中的第一行为true,则首先使用TRUE更新字段A的其余部分。但是我不知道该怎么做。

  2. 具有一个基于行本身但基于标题行的过滤器。再说一次,我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)


这些是基于选项1建议的解决方案:

# Import pandas
import pandas as pd
import numpy as np

# Sample df
d = {'FieldA': [True, '', '', '', '', False, '', '', '', ''],'FieldB': [1, 2, 1, 4, 6, 5, 7, 9, 0, 1], 'FieldC': [0.3, 0.2, 0.3, 0.2, 0.2, 0.3, 0.2, 0.3, 0.2, 0.2]}
df = pd.DataFrame(data=d)

# Create temporaty column to find index distance from last True/False
t_mod = []
for i in list(df.index.values):
    t_mod.append(i%5)

df['t_mod_c'] = np.array(t_mod)

Output

 # Add missinf True/False values to FieldA based in column t_mod_c
test = []
for i in df.index.values:
    test.append(df['FieldA'].loc[i-df['t_mod_c'].loc[i]])
df.drop(['t_mod_c'], axis=1, inplace = True)
df['FieldA'] = np.array(test)
df

enter image description here

# Sum FieldB based on FieldA value
df[df['FieldA'] == True]['FieldB'].sum()

希望有帮助!
如果您有其他问题,请通知我。
祝你好运!