我有一个两列的DataFrame df
,它的列是phone
和label
,其中label
可以只能是 0 或 1。
这是一个例子:
phone label
a 0
b 1
a 1
a 0
c 0
b 0
我想要做的是计算每种“电话”类型的“1”的数量,并使用该数字替换“电话”列
我想到的是 groupby
,但我不熟悉它
答案应该是:
Count the number of each 'phone'
phone count
a 1
b 1
c 0
replace the 'phone' with 'count' in the original table
phone
1
1
1
1
0
1
最佳答案
考虑到label
列只能有0
或1
,可以使用.trasnform('sum')方法:
In [4]: df.label = df.groupby('phone')['label'].transform('sum')
In [5]: df
Out[5]:
phone label
0 a 1
1 b 1
2 a 1
3 a 1
4 c 0
5 b 1
说明:
In [2]: df
Out[2]:
phone label
0 a 0
1 b 1
2 a 1
3 a 0
4 c 0
5 b 0
In [3]: df.groupby('phone')['label'].transform('sum')
Out[3]:
0 1
1 1
2 1
3 1
4 0
5 1
dtype: int64
关于python - Pandas DataFrame 使用另一列更新一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38387062/