簡體   English   中英

pandas dataframe groupby 不丟失被分組的列

[英]pandas dataframe groupby without losing the column which was grouped

在我發布的一篇文章中,我在根據某些條件刪除/求和行時遇到問題,有人幫助糾正了這樣的代碼。

這是我的代碼:

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 方法時,它會丟棄car columns 誰可以幫我這個事?

我得到了這個 output:

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

預期 output:

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

您需要聚合列以將其保留在輸出中(或by參數傳遞給id ),因此為避免丟失cars列,使用聚合 function 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

我相信它正在發生,因為cars是非數字的,默認情況下在 DataFrame 總和上會跳過它。 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

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)


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM