【问题标题】:pandas dataframe groupby without losing the column which was grouped熊猫数据框 groupby 不丢失分组的列
【发布时间】:2021-06-23 19:17:27
【问题描述】:

last post 上,我发布了我在根据特定条件删除/求和行时遇到问题,并且有人帮助纠正了这样的代码。

这是我的代码:

import pandas as pd
df=pd.DataFrame({
                'cars':['Kia rio','Bmw','Mercedes','Ford','Kia','Mercedes Benz'],
                'rent':[1,1,2,1,4,2],
                'sale':[2,4,1,1,5,1],
                'id':[2000,1000,3000,4000,2000,3000]
                })
print(df)
df1 = df.drop_duplicates().groupby(['id'], sort=False, as_index=False).sum()
print(df1)

但是当我运行 groupby 方法时,它会丢弃 汽车列。谁能帮我解决这个问题?

我得到了这个输出:

     id  rent  sale
0  2000     5     7
1  1000     1     4
2  3000     4     2
3  4000     1     1

预期输出:

    cars    rent  sale  id
   Kia         5     7  2000
      Bmw      1     4  1000
     Mercedes  2     1  3000
        Ford   1     1  4000

【问题讨论】:

  • 为什么Kia在输出中是2次?
  • 我编辑了代码谢谢

标签: python pandas dataframe


【解决方案1】:

您需要聚合列以将其保留在输出中(或传递给by 参数,如id),因此为了避免丢失cars 列,使用聚合函数last 来获取每组cars 的最后一个值,也为另外 2 列指定聚合 sum

df1 = df.drop_duplicates().groupby('id',sort=False,as_index=False).agg(cars=('cars','last'),
                                                                       rent=('rent', 'sum'),
                                                                       sale=('sale', 'sum'))
print(df1)
     id           cars  rent  sale
0  2000            Kia     5     7
1  1000            Bmw     1     4
2  3000  Mercedes Benz     4     2
3  4000           Ford     1     1

如果可能,split carnames 按第一个空格并按 idcars 聚合:

df['cars'] = df['cars'].str.split().str[0]
df1 = df.drop_duplicates().groupby(['id','cars'], sort=False, as_index=False).sum()
print(df1)
     id      cars  rent  sale
0  2000       Kia     5     7
1  1000       Bmw     1     4
2  3000  Mercedes     2     1
3  4000      Ford     1     1

【讨论】:

  • @AhmedChater - 数据中有'Mercedes','Mercedes Benz',所以值不同,所以drop_duplicates() 没有被删除。
【解决方案2】:

我相信它正在发生,因为cars 是非数字的,默认情况下会在 DataFrame sum 上跳过它。 Sum 有一个可选参数numeric_onlybool,它表示:

numeric_onlybool, default None

    Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.

来源: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sum.html

这个问题也有一些关于分组字符串部分的好信息: Pandas groupby: How to get a union of strings

【讨论】:

    【解决方案3】:
    import pandas as pd
    df = pd.DataFrame({
                    'cars':['Kia rio', 'Bmw', 'Mercedes', 'Ford', 'Kia', 'Mercedes Benz'],
                    'rent':[1, 1, 2, 1, 4, 2],
                    'sale':[2, 4, 1, 1, 5, 1],
                    'id': [2000, 1000, 3000, 4000, 2000, 3000]
                    })
    print(df)
    df1 = df.drop_duplicates().groupby(['id', 'cars'], sort=False, as_index=False).sum()
    print(df1)
    
    
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 2022-01-12
      • 2023-01-12
      • 2016-10-09
      • 2013-12-19
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多