gpt4 book ai didi

python - 对特定列中的行中的特定整数值进行计数

转载 作者:太空宇宙 更新时间:2023-11-03 20:29:47 24 4
gpt4 key购买 nike

我有 pandas 数据框,有 12 列,每列的值随机为 0 到 12。我想创建新列,其中包含这些特定值的计数。例如 newvar1 将在每行中包含“1”的计数。另一个新的结果变量将包含某些特定列中某些特定值的计数

我的数据框是这样的

v1 v2 v3 v4 
0 1 2 1
2 3 1 1

我想要的输出就像

v1 v2 v3 v4 newvar1_count_of_1 newvar1_count_of_1_ in_first_2_col
0 1 2 1 2 1
2 3 1 1 2 0

最佳答案

你只应该这样做:

df1['newvar1_count']=df1[df1.eq(1)].sum(axis=1)
df1['newvar1_count_of_1_ in_first_2_col']=df1[df1.eq(1)].loc[:,['v1','v2']].sum(axis=1)

应用到您的代码中:

df1['newvar1_count'] = df1.eq(1).sum(axis=1)
df1['newvar1_count_of_1_ in_first_2_col']=df1[df1.eq(1)].loc[:,['v1','v2']].sum(axis=1)
df1

输出:

    v1  v2  v3  v4  newvar1_count   newvar1_count_of_1_ in_first_2_col
0 0 1 2 1 2.0 1.0
1 2 3 1 1 2.0 0.0

关于python - 对特定列中的行中的特定整数值进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57579874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com