如何在熊猫数据框中找到混合类别变量的均值?

时间:2019-03-01 00:28:12

标签: python pandas

我使用各种社交媒体平台收集了有关不同年龄段人群的调查数据集。我想计算社交媒体应用使用情况下的平均人数。示例数据如下所示:

enter image description here

这是可复制的熊猫数据框:

df=pd.DataFrame({'age': np.random.randint(10,100,size=10),
                'web1a': np.random.choice([1, 2], size=(10,)),
                'web1b': np.random.choice([1, 2], size=(10,), p=[1./3, 2./3]),
                'web1c': np.random.choice([1, 2], size=(10,)),
                'web1d': np.random.choice([1, 2], size=(10,))})

这是我尝试过的:

df.pivot_table(df, values='web1a', index='age', aggfunc='mean')

但是效率不高,没有产生我想要的输出。有什么想法可以完成吗?谢谢

更新

对我来说,执行此操作的方法是,首先在每列中选择类别值,然后为其取平均值,而其他均值可以相同。如果这样做,如何绘制好它们?

请注意,在web1aweb1bweb1cweb1d1栏中分别表示用户和2表示非用户。我想计算用户和非用户的平均年龄。我怎样才能做到这一点?有人给我一个可能的想法来实现这一目标吗?谢谢!

4 个答案:

答案 0 :(得分:2)

您可以对“网络*”列进行分组,并在“年龄”列中计算平均值。

您还可以绘制条形图(可以在子图中定义颜色)。在这种情况下,我不确定饼图是否有意义。

我尝试了您的data,仅采用了以“ web”开头的列。值比“ 1”和“ 2”多,因此我假设您只想分析用户和非用户,而没有其他东西。只要知道要绘制的值,就可以用相同的方法更改值或在图表中添加其他值。

df = df.filter(regex=('web|age'),axis=1)

userNr = '1'
nonUserNr = '2'
users = list()
nonUsers = list()
labels = [x for x in df.columns.tolist() if 'web' in x]
for col in labels:
    users.append(df.loc[:,['age',col]].groupby(col).mean().loc[userNr][0])
    nonUsers.append(df.loc[:,['age',col]].groupby(col).mean().loc[nonUserNr][0])

from matplotlib import pyplot as plt
x = np.arange(1, len(labels)+1)
ax = plt.subplot(111)
ax.bar(x-0.1, users, width=0.2,color='g')
ax.bar(x+0.1,nonUsers, width=0.2,color='r')
plt.xticks(x, labels)
plt.legend(['users','non-users'])
plt.show()

enter image description here

答案 1 :(得分:2)

使用

df.melt('age').set_index(['variable','value']).mean(level=[0,1]).unstack().plot(kind='bar')

enter image description here

答案 2 :(得分:1)

这可以使用groupby方法完成:

df.groupby(['web1a', 'web1b', 'web1c', 'web1d']).mean()

答案 3 :(得分:1)

<div id="footer">Footer - Just scroll...</div>

enter image description here