python - Pandas DataFrame 使用另一列更新一列

标签 python pandas dataframe group-by

我有一个两列的DataFrame df,它的列是phonelabel,其中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列只能有01,可以使用.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/

相关文章:

python - 取最近N天的平均值

python - pandas 按列分组,查找多列的最小值,并为组中的最小行创建新列

python - 在 pandas 数据框中的列表中搜索

python - 如何通过 class 属性包含空格的 css 选择器匹配特定标签?

python - 使用 POST 数据向用户确认通用 FormView POST 成功

python-3.x - python : Extract dimension data from dataframe string column and create columns with values for each of them

python - 如何使用 apply 函数删除大数据框中的单词

python - 如何将数据框转换为字典

python - 通过变量获取属性

python - 如何在 python 中正确地将 float /小数截断到小数点后的特定位置?