【问题标题】:Selecting column from multi-index dataframe, to make for example an histogram从多索引数据框中选择列,例如制作直方图
【发布时间】:2019-06-12 10:31:19
【问题描述】:

这是我第一次使用多索引数据帧。我有一个看起来像这样的数据框(小例子):

import random
col3=[0,0,0,0,2,4,6,0,0,0,100,200,300,400]
col4=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]

d = {'Unit': [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6], 
 'Year': [2014, 2015, 2016, 2017, 2015, 2016, 2017, 2017, 2014, 2015, 2014, 2015, 2016, 2017], 'col3' : col3, 'col4' : col4 }
df = pd.DataFrame(data=d)
df.groupby(['Unit', 'Year']).sum()

df = df.groupby(['Unit', 'Year']).sum()

df['mask'] = (df.groupby(level=0, group_keys=False)
                  .apply(lambda x: x.col3/x.col4.shift()))

df['mask'] = df['mask'].fillna(0) 

现在我想根据掩码列中的值制作直方图,如果不先制作列表,这可能吗?

我是这样做的:

values = [x for x in df['mask']]
plt.hist(values)

但我想最好不要中间列表步骤。

谢谢,

【问题讨论】:

  • 你需要plt.hist(df['mask'])吗?
  • 你试过df['mask'].plot(kind='hist')吗?

标签: python pandas histogram multi-index


【解决方案1】:

这里的列表理解不是必需的,只需将Series传递给plot

plt.hist(df['mask'])

或者使用Series.plot.hist:

df['mask'].plot.hist()

【讨论】:

  • 感谢您的回答。 Series.plot.hist 的第二种方法对我有用。我的数据集非常大,还包含 -inf 值。因此,通过该方法,我可以使用以下内容创建历史记录:df.A_4170_10_log[df['mask'] != -np.inf].plot.hist(bins = 50). 但是plt.hist(df['mask']) 给出以下错误:ValueError: max must be larger than min in range parameter.])。你知道有什么问题吗?
  • @jenny - 嗯,不知道。如果使用plt.hist(df.loc[df['mask'] != -np.inf, 'mask']) 不起作用?
猜你喜欢
  • 1970-01-01
  • 2020-01-12
  • 2018-12-25
  • 2021-09-08
  • 2018-05-28
  • 2021-12-05
  • 2020-04-27
  • 2023-02-23
  • 2015-01-25
相关资源
最近更新 更多