【发布时间】:2016-05-26 16:09:55
【问题描述】:
我想在 pandas DataFrame 上运行一个支点,索引是两列,而不是一列。例如,一个字段表示年份,一个字段表示月份,一个显示“item 1”和“item 2”的“item”字段以及一个带有数值的“value”字段。我希望索引为年 + 月。
我设法使它工作的唯一方法是将两个字段合并为一个,然后再次将它们分开。有没有更好的办法?
下面复制的最小代码。非常感谢!
PS 是的,我知道关键字“pivot”和“multi-index”还有其他问题,但我不明白他们是否/如何帮助我解决这个问题。
import pandas as pd
import numpy as np
df= pd.DataFrame()
month = np.arange(1, 13)
values1 = np.random.randint(0, 100, 12)
values2 = np.random.randint(200, 300, 12)
df['month'] = np.hstack((month, month))
df['year'] = 2004
df['value'] = np.hstack((values1, values2))
df['item'] = np.hstack((np.repeat('item 1', 12), np.repeat('item 2', 12)))
# This doesn't work:
# ValueError: Wrong number of items passed 24, placement implies 2
# mypiv = df.pivot(['year', 'month'], 'item', 'value')
# This doesn't work, either:
# df.set_index(['year', 'month'], inplace=True)
# ValueError: cannot label index with a null key
# mypiv = df.pivot(columns='item', values='value')
# This below works but is not ideal:
# I have to first concatenate then separate the fields I need
df['new field'] = df['year'] * 100 + df['month']
mypiv = df.pivot('new field', 'item', 'value').reset_index()
mypiv['year'] = mypiv['new field'].apply( lambda x: int(x) / 100)
mypiv['month'] = mypiv['new field'] % 100
【问题讨论】:
-
我在Q&A中提供了几个详细的示例和替代方法
标签: python pandas pivot multi-index