如何根据不同 df 中提供的索引值对数据框中的特定列求和? Return 总和和布尔值 T/F

How can I Sum specific columns in a dataframe based on index value provided in a different df. Return the sum and Boolean T/F

我有两个 pandas 数据帧。 df_lst包含列名列表和期望值,df有一系列数据。

df_lst 中的列名称可能会更改,我使用以下脚本从 df 中查找列索引与 df_lst 中的列名对齐显示此代码以防它是可能不需要的额外步骤。

ind_dict = dict((k,i) for i,k in enumerate(d.columns))
inter = set(df_lst['Col_Name']).intersection(df)
df_lst['Index'] = [ ind_dict[x] for x in inter ]

此任务的输入如下所示:

import random
import numpy as np
import pandas as pd

a = np.random.randint(12, size=(7, 11))
df = pd.DataFrame(a, ['foo','foo','bar', 'bar', 'bar', 'foo', 'foo'], ['a','b','f','g','h','j' ,'k', 'r', 's', 't', 'z'])

df_lst = pd.DataFrame({'Col_Name': ['Col_g', 'Col_j', 'Col_r', 'Col_s'], 
                   'Expected Value': [100, 90, 122, 111],                                      
                   'Index': [4, 6, 8, 9]})

如何使用新的索引值查看 df 中的相应列并对值求和,return 求和值和 'True' 如果大于或 'False' 如果小于 df_lst

中的每一行
df_out = pd.DataFrame({'Col_Name': ['Col_g', 'Col_j', 'Col_r', 'Col_s'], 
                   'Expected Value': [100, 90, 122, 111],                                      
                   'Index': [4, 6, 8, 9],
                   'Sum of Col': ['sum of col_g', 'sum of col_j', 'sum of col_r', 'sum of col_s'],
                   'Bool': ['True or False', 'True or False', 'True or False', 'True or False']
                   })

最终,这个 True/False 数据将成为 while 循环的一部分,该循环检查类似“while 1 or more is false do X”之类的东西

我们可以使用 df_lst['Index']iloc we will need to subtract 1 to convert from 1 based indexing to 0 based. Then sum the column and join 中的值 select 来自 df 的值返回到 DataFrame。然后我们可以根据新的 Sum of Col 值计算 Bool 列:

df_out = df_lst.join(
    df.iloc[:, df_lst['Index'] - 1].sum()
        .add_prefix('Col_')
        .rename('Sum of Col'),
    on='Col_Name'
)

df_out['Bool'] = df_out['Sum of Col'] > df_out['Expected Value']

df_out:

  Col_Name  Expected Value  Index  Sum of Col   Bool
0    Col_g             100      4         106   True
1    Col_j              90      6          97   True
2    Col_r             122      8          95  False
3    Col_s             111      9         113   True

步骤:

Select 和 iloc 请注意,整数索引从 0 开始,因此 g 列位于索引 3 而不是 4:

df.iloc[:, df_lst['Index'] - 1]

      g   j   r   s
foo   0   7  14  16
foo  23  13  12  12
bar   5  13   3  16
bar  17  13  24  16
bar  24  14  11  23
foo  17  19  24  17
foo  20  18   7  13

列总和 sum:

df.iloc[:, df_lst['Index'] - 1].sum()
Out[3]: 
g    106
j     97
r     95
s    113
dtype: int64

add_prefix so columns match Col_Name column and rename 系列,以便新列具有正确的名称:

df.iloc[:, df_lst['Index'] - 1].sum().add_prefix('Col_').rename('Sum of Col')

Col_g    106
Col_j     97
Col_r     95
Col_s    113
Name: Sum of Col, dtype: int64

join 连同 df_lst:

df_lst.join(
    df.iloc[:, df_lst['Index'] - 1].sum()
        .add_prefix('Col_')
        .rename('Sum of Col'),
    on='Col_Name'
)

  Col_Name  Expected Value  Index  Sum of Col
0    Col_g             100      4         106
1    Col_j              90      6          97
2    Col_r             122      8          95
3    Col_s             111      9         113

进行任何需要的比较并添加任何额外的列:

df_out['Bool'] = df_out['Sum of Col'] > df_out['Expected Value']

  Col_Name  Expected Value  Index  Sum of Col   Bool
0    Col_g             100      4         106   True
1    Col_j              90      6          97   True
2    Col_r             122      8          95  False
3    Col_s             111      9         113   True

可重现的设置:

import pandas as pd
from numpy.random import Generator, MT19937

rng = Generator(MT19937(25))
a = rng.integers(25, size=(7, 11))
df = pd.DataFrame(a, ['foo', 'foo', 'bar', 'bar', 'bar', 'foo', 'foo'],
                  ['a', 'b', 'f', 'g', 'h', 'j', 'k', 'r', 's', 't', 'z'])

df_lst = pd.DataFrame({'Col_Name': ['Col_g', 'Col_j', 'Col_r', 'Col_s'],
                       'Expected Value': [100, 90, 122, 111],
                       'Index': [4, 6, 8, 9]})