首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在dataframe中遍历每一列并执行计算?

如何在dataframe中遍历每一列并执行计算?
EN

Stack Overflow用户
提问于 2018-04-06 18:45:39
回答 1查看 72关注 0票数 0

因此,我使用plt.subplots()在一个输出中绘制多个图,同时使用matplotlib魔术函数。

无论如何,我注意到我对每个“变量”(或列)对我的数据进行了相同的计算。基本上,它看起来像这样

代码语言:javascript
复制
%matplotlib inline

fig, (ax1,ax2,ax3) =plt.subplots(nrows=1, ncols=3, sharex=False, sharey=True, figsize=(5,5))

#PAPERLESS

ACCOUNT= df.groupby(['PAPERLESS'])['ACCOUNT'].count().rename('ACCOUNT')
cases=df.groupby(['PAPERLESS'])['cases'].sum().rename('cases')
paperless=pd.concat([ACCOUNT,cases],axis=1)
tempdf=paperless
tempdf['percent']=tempdf['cases']/tempdf['ACCOUNT']*100
print(tempdf)
graph1=tempdf['percent'].plot(y='percent',kind='bar', ax=ax1)
ax1.set_title("Paperless")
graph1.yaxis.set_major_formatter(mtick.PercentFormatter())

plt.tight_layout()

因此,我显然是从“无纸化”变量开始,获取数据中每一列的计费计数。现在,我想计算每个变量的帐户,从我的案例数中找出它们的百分比,然后绘制它。如何使用函数或某种类型的for循环来实现这一点?我有大约15个变量,所以手动操作并不是很有效.

谢谢,我将更新我提出的问题,因为这个问题是公开的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-06 19:25:40

我想这能帮你做到

代码语言:javascript
复制
import pandas as pd
%matplotlib inline

fig, axes =plt.subplots(nrows=1, ncols=3, sharex=False, sharey=True, figsize=(5,5))

aggregators = {'ACCOUNT':'count', 'cases': 'sum'}
variables = ['PAPERLESS', 'More PAPERLESS', 'PAPEERLESS NOT'] #For example
'''
# One way to get all the variables
variables = list(df.columns)
variables.remove('ACCOUNT')
variables.remove('cases')
'''

for variable, ax in zip(variables, axes):
    mid = df.groupby(variable)['ACCOUNT', 'cases'].agg(aggregators) #Map a function to each column
    percts = (mid.ACCOUNT / mid.cases) * 100 #Return a pd.Series with the percentages since you only plot that anyways
    percts.plot(kind='bar', ax=ax) #Only plot percentage
    ax.set_title(variable)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49699247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档