【问题标题】:Assign Column name to the column in a DataFrame将列名分配给 DataFrame 中的列
【发布时间】:2018-12-20 20:36:06
【问题描述】:

这是我的代码,

avg_data = dataset.groupby('Gender').mean()
print(avg_data)

输出:

            Height      Weight     Index
Gender                                  
Female  170.227451  105.698039  3.709804
Male    169.648980  106.314286  3.787755

我想使用 countplot 绘制这些数据。

sns.countplot(x='Gender',hue='Height',data=avg_data)

错误!

ValueError                                Traceback (most recent call 
last)
<ipython-input-54-59e9d525d88d> in <module>
----> 1 sns.countplot(x='Gender',hue='Height',data=avg_data)

/usr/local/lib/python3.6/dist-packages/seaborn/categorical.py in 
countplot(x, y, hue, data, order, hue_order, orient, color, palette, 
saturation, dodge, ax, **kwargs)
3551                           estimator, ci, n_boot, units,
3552                           orient, color, palette, saturation,
-> 3553                           errcolor, errwidth, capsize, dodge)
3554 
3555     plotter.value_label = "count"

/usr/local/lib/python3.6/dist-packages/seaborn/categorical.py in 
__init__(self, x, y, hue, data, order, hue_order, estimator, ci, 
n_boot, units, orient, color, palette, saturation, errcolor, errwidth, 
capsize, dodge)
1605         """Initialize the plotter."""
1606         self.establish_variables(x, y, hue, data, orient,
-> 1607                                  order, hue_order, units)
1608         self.establish_colors(color, palette, saturation)
1609         self.estimate_statistic(estimator, ci, n_boot)

/usr/local/lib/python3.6/dist-packages/seaborn/categorical.py in 
establish_variables(self, x, y, hue, data, orient, order, hue_order, 
units)
153                 if isinstance(input, string_types):
154                     err = "Could not interpret input 
'{}'".format(input)
--> 155                     raise ValueError(err)
156 
157             # Figure out the plotting orientation

ValueError: Could not interpret input 'Gender'

它检测到没有“性别”列。如何解决?

【问题讨论】:

  • 用as_index=False尝试groupby

标签: python python-3.x pandas


【解决方案1】:

现在,Gender 是结果数据帧的索引。 只需在此命令上执行 reset_index():

avg_data = dataset.groupby('Gender').mean().reset_index()

或

avg_data = dataset.groupby('Gender', as_index=False).mean()

这将创建Gender 作为您可以在其上绘制的数据框的一列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 2015-04-14
    • 2017-12-03
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多