San*_*eev 9 python python-3.x pandas
这显然很简单,但作为一只熊猫,我会陷入困境.
我有一个包含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)]})
Run Code Online (Sandbox Code Playgroud)
我正在尝试以下内容,但它给了我一个错误:'没有连接的对象'
df['ratio'] = df.groupby(['state']).agg(df['bene_1_count']/df['bene_2_count'])
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何"达到"群组的状态级别来获取列的比率.
我希望列的比例与状态相似,就像我想要的输出如下:
State ratio
CA
WA
CO
AZ
Run Code Online (Sandbox Code Playgroud)
ans*_*onw 10
或者,声明:您可以创建接受数据框的自定义函数.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)
Run Code Online (Sandbox Code Playgroud)
现在假设您希望每行除以每组的总和(例如,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)
Run Code Online (Sandbox Code Playgroud)