簡體   English   中英

Pandas透視表使用數據框上的自定義條件

[英]Pandas pivot table using custom conditions on the dataframe

我想根據數據框中的自定義條件制作數據透視表:

數據框如下所示:

>>> df = pd.DataFrame({"Area": ["A", "A", "B", "A", "C", "A", "D", "A"],
                       "City" : ["X", "Y", "Z", "P", "Q", "R", "S", "X"],
                       "Condition" : ["Good", "Bad", "Good", "Good", "Good", "Bad", "Good", "Good"], 
                       "Population" : [100,150,50,200,170,390,80,100]
                       "Pincode" : ["X1", "Y1", "Z1", "P1", "Q1", "R1", "S1", "X2"] })
>>> df
  Area City Condition   Population Pincode
 0    A    X      Good   100       X1
 1    A    Y       Bad   150       Y1
 2    B    Z      Good   50        Z1
 3    A    P      Good   200       P1
 4    C    Q      Good   170       Q1
 5    A    R       Bad   390       R1
 6    D    S      Good   80        S1
 7    A    X      Good   100       X2

現在我想以一種方式來轉動數據框df ,這樣我就可以看到針對每個區域的城市的唯一計數以及相應的“好”城市數量以及該區域的人口數量。

我期待這樣的輸出:

Area  city_count  good_city_count   Population
A        4        2                 940
B        1        1                 50
C        1        1                 170
D        1        1                 80
All      7        5                 1240

我可以給aggfunc參數一個字典,但這並沒有給我好城市之間的城市數量。

>>> city_count = df.pivot_table(index=["Area"],
                                values=["City", "Population"],
                                aggfunc={"City": lambda x: len(x.unique()),
                                         "Population": "sum"},
                                margins=True)

    Area    City    Population
0   A       4       940
1   B       1       50
2   C       1       170
3   D       1       80
4   All     7       1240

我可以合並兩個不同的數據透視表 - 一個具有城市數量,另一個具有總體數量但是對於具有大型aggfunc字典的大型數據集而言,這是不可擴展的。

使用fill_value添加新參數columns ,也可以使用nunique作為聚合函數:

city_count = df.pivot_table(index = "Area", 
                            values = "City", 
                            columns='Condition', 
                            aggfunc = lambda x : x.nunique(), 
                            margins = True,
                            fill_value=0)
print (city_count)
Condition  Bad  Good  All
Area                     
A            2     2    4
B            0     1    1
C            0     1    1
D            0     1    1
All          2     5    7

最后如果需要將索引轉換為列並更改列名稱:

city_count = city_count.add_suffix('_count').reset_index().rename_axis(None, 1)
print (city_count)
  Area  Bad_count  Good_count  All_count
0    A          2           2          4
1    B          0           1          1
2    C          0           1          1
3    D          0           1          1
4  All          2           5          7

編輯:

d = {'City':'nunique','Population':'sum', 'good_city_count':'nunique'}
d1 = {'City':'city_count','Condition':'good_city_count'}

mask = df["Condition"] == 'Good'
df = (df.assign(good_city_count = lambda x: np.where(mask, x['City'], np.nan))
       .groupby('Area')
       .agg(d)
       .rename(columns=d1))

df = df.append(df.sum().rename('All')).reset_index()

print (df)
  Area  city_count  Population  good_city_count
0    A           4         940                2
1    B           1          50                1
2    C           1         170                1
3    D           1          80                1
4  All           7        1240                5

不使用pivot_table另一種方法。 使用帶有groupby + agg np.where

df['Condition'] = np.where(df['Condition']=='Good', df['City'], np.nan)
df = df.groupby('Area').agg({'City':'nunique', 'Condition':'nunique', 'Population':'sum'})\
                       .rename(columns={'City':'city_count', 'Condition':'good_city_count'})
df.loc['All',:] = df.sum()
df = df.astype(int).reset_index()

print(df)
  Area  city_count  good_city_count  Population
0    A           4                2         940
1    B           1                1          50
2    C           1                1         170
3    D           1                1          80
4  All           7                5        1240

暫無
暫無

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

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