python - 如果差异大于 Pandas 中的列值,则将两个 pandas 列值的差异添加到新行

标签 python pandas pandas-groupby

''' 这是我拥有的数据样本 '''

PERIOD GROUP USER_COUNT REGION
50    A     55            AX
25    A     20            AX
30    B     33            BY
40    C     10            CZ

预期输出

PERIOD GROUP USER_COUNT REGION
50    A        50         AX
50    A         5         AX
25    A        20         AX
30    B        30         BY
30    B        3          BY
40    C        10         CZ

最佳答案

用途:

#get difference of columns
s = df['USER_COUNT'].sub(df['PERIOD']) 
#mask for positive subtract values
m = s > 0

#subtract of original data ony matched rows of column VAL2
df1 = df.assign(USER_COUNT = lambda x: x['USER_COUNT'].sub(s[m], fill_value=0))
#overwrite matched rows
df2 = df[m].assign(USER_COUNT = s[m])

#join together and sorting by only stable sorting - mergesort
df3 = (pd.concat([df1, df2])
         .sort_index(kind='mergesort')
         .reset_index(drop=True)
         .astype(df.dtypes))
print (df3)
   PERIOD GROUP  USER_COUNT REGION
0      50     A          50     AX
1      50     A           5     AX
2      25     A          20     AX
3      30     B          30     BY
4      30     B           3     BY
5      40     C          10     CZ

关于python - 如果差异大于 Pandas 中的列值,则将两个 pandas 列值的差异添加到新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60167717/

相关文章:

python - 如何将随机森林中选定的特征转换为新列表

python - Discord.py @bot.event

python - 为什么我的(局部)变量表现得像全局变量?

python - vscode "no refactorings available"for python

python - Pandas 在第 0 个位置插入空行

python - 如何使用 python 在新数据框中复制当前行和下一行值?

python - Pandas 数据框 : how to permute rows and create new groups of combinations

python - 要计算每个 'option' 和 'Type' 每年出现的次数,

python - 使用计数比率的附加列对 DataFrame 进行分组和旋转

python - 按天过滤 Pandas 数据框