python - 我的 pandas 数据框中有两列。一列有一些相同的值(id),另一列中的相应值有票数

标签 python pandas dataframe pandas-groupby

   id         n_tickets
0  1586391          2
1   640             2
2   640             1
3  1181593          2
4   964842          1
5    780            1
6    780            1  

我有上面的数据框。正如您所看到的,在 id 列 640 和 780 中出现了两次。我希望只保留一次出现,但 n_tickets 列中的相应值会被累加。我的最终数据框应如下所示:

     id         n_tickets
0  1586391          2
1   640             3
2  1181593          2
3   964842          1
4    780            2 

我正在使用代码:df_tickets.groupby(['id','n_tickets']).sum()但我收到错误:

Empty DataFrame
Columns: []
Index: []

当我使用以下代码时:

df_tickets.groupby('id',sort=False).sum().reset_index()

print(df_tickets.loc[df_tickets['id'] == 780])

我明白了:

        id     n_tickets
425166  780          1
985855  780          1

相反,我应该得到:

           id    n_tickets
   425166  780      2

最佳答案

您只需按“id”分组即可:

df.groupby('id',sort=False).sum().reset_index()
Out[60]: 
        id  n_tickets
0  1586391          2
1      640          3
2  1181593          2
3   964842          1
4      780          2

当我使用上面的代码时:

df_tickets.groupby('id',sort=False).sum().reset_index()

    print(df_tickets.loc[df_tickets['id'] == 780])

我明白了:

         id     n_tickets
425166  780          1
985855  780          1

相反,我应该得到:

    id    n_tickets
 425166  780      2

关于python - 我的 pandas 数据框中有两列。一列有一些相同的值(id),另一列中的相应值有票数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162051/

相关文章:

python - 如何在python中的正则表达式搜索函数中使用变量而不是字符串

python - 如何根据 Pandas 其他两列中的查找值分配最小值?

python - 如何知道一个词的具体TF-IDF值?

python - 如何对数据集中的某些单词进行值计数

python - 将前 1...N 个月的值移动为单独的列

python - 构建饼图

python - astype Pandas 上的错误?

python - 如何将多次出现的二进制列转换为 Pandas 中的分类数据

python - 从 matplotlib 中选定的列绘制条形图

python - 从 pandas 网站读取大型数据集仅返回 1.000 行?