[英]Pandas division of two columns with groupby
這顯然很簡單,但作為一只熊貓,我會陷入困境。
我有一個包含3列的CSV文件,State,bene_1_count和bene_2_count。
我想計算給定狀態下'bene_1_count'和'bene_2_count'的比例。
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'bene_1_count': [np.random.randint(10000, 99999)
for _ in range(12)],
'bene_2_count': [np.random.randint(10000, 99999)
for _ in range(12)]})
我正在嘗試以下內容,但它給了我一個錯誤:'沒有連接的對象'
df['ratio'] = df.groupby(['state']).agg(df['bene_1_count']/df['bene_2_count'])
我無法弄清楚如何“達到”群組的狀態級別來獲取列的比率。
我希望列的比例與狀態相似,就像我想要的輸出如下:
State ratio
CA
WA
CO
AZ
或者,聲明:您可以創建接受數據框的自定義函數。 groupby將返回子數據幀。 然后,您可以使用apply函數將自定義函數應用於每個子數據幀。
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'bene_1_count': [np.random.randint(10000, 99999)
for _ in range(12)],
'bene_2_count': [np.random.randint(10000, 99999)
for _ in range(12)]})
def divide_two_cols(df_sub):
return df_sub['bene_1_count'].sum() / float(df_sub['bene_2_count'].sum())
df.groupby('state').apply(divide_two_cols)
現在假設您希望每行除以每組的總和(例如,AZ的總和)並保留所有原始列。 只需調整上述功能(更改計算並返回整個子數據幀):
def divide_two_cols(df_sub):
df_sub['divs'] = df_sub['bene_1_count'] / float(df_sub['bene_2_count'].sum())
return df_sub
df.groupby('state').apply(divide_two_cols)
我相信你首先需要做的是在找到比率之前按州計算。 您可以使用apply
訪問df中的其他列,然后將它們存儲在字典中以映射到原始數據幀中的相應狀態。
import pandas as pd
import numpy as np
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'bene_1_count': [np.random.randint(10000, 99999)
for _ in range(12)],
'bene_2_count': [np.random.randint(10000, 99999)
for _ in range(12)]})
ratios = df.groupby('state').apply(lambda x: x['bene_1_count'].sum() /
x['bene_2_count'].sum().astype(float)).to_dict()
df['ratio'] = df['state'].map(ratios)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.