Pivot table 不使用数据帧中的 datetimeindex 创建
Pivot table not creating with datetimeindex from dataframe
我在使用日期时间索引作为索引的数据帧创建数据透视表时遇到问题 table。编辑以显示完整代码
有问题的代码是
unit1 = ["U1", "U1", "U1", "U1", "U1", "U1"]
name1 = ["fn ln", "fn ln2", "fn ln3", "fn ln4", "fn ln5", "fn ln6"]
count1 = [2,4,6,8,10,12]
df = pd.DataFrame( {'Date': pd.Timestamp('2016-01-01'),
'Unit': unit1,
'Name"': name1,
'Count': count1})
df2 = df.set_index(pd.DatetimeIndex(df.Date))
df2['Month'] = df2.index.month
# this line succeeds
pt = pd.pivot_table(df, index=df2.index.month, values='Count')
# this line fails with Series object has no attribute month
pt = pd.pivot_table(df, index=df2.Month.month, values='Count')
数据帧的内部结构 (_stat_axis) 显示索引字段是 DatetimeIndex。 month 列也有 datetimeindex 设置,但创建 pivot table 仍然会出现 Series 错误。
也许您可以将参数 values
添加到 pivot_table
:
print df
Unit Name Count
2013-01-01 U1 fn ln 2
2013-01-01 U1 fn ln 200
2013-01-01 U2 fn ln 55
print pd.pivot_table(df, index=df.index.month, values="Count", aggfunc=np.sum)
1 257
Name: Count, dtype: int64
我在使用日期时间索引作为索引的数据帧创建数据透视表时遇到问题 table。编辑以显示完整代码
有问题的代码是
unit1 = ["U1", "U1", "U1", "U1", "U1", "U1"]
name1 = ["fn ln", "fn ln2", "fn ln3", "fn ln4", "fn ln5", "fn ln6"]
count1 = [2,4,6,8,10,12]
df = pd.DataFrame( {'Date': pd.Timestamp('2016-01-01'),
'Unit': unit1,
'Name"': name1,
'Count': count1})
df2 = df.set_index(pd.DatetimeIndex(df.Date))
df2['Month'] = df2.index.month
# this line succeeds
pt = pd.pivot_table(df, index=df2.index.month, values='Count')
# this line fails with Series object has no attribute month
pt = pd.pivot_table(df, index=df2.Month.month, values='Count')
数据帧的内部结构 (_stat_axis) 显示索引字段是 DatetimeIndex。 month 列也有 datetimeindex 设置,但创建 pivot table 仍然会出现 Series 错误。
也许您可以将参数 values
添加到 pivot_table
:
print df
Unit Name Count
2013-01-01 U1 fn ln 2
2013-01-01 U1 fn ln 200
2013-01-01 U2 fn ln 55
print pd.pivot_table(df, index=df.index.month, values="Count", aggfunc=np.sum)
1 257
Name: Count, dtype: int64