我有一个CSV,看起来像这样:
name,location,sales,customer_count
john,fairfax,1000,400
jane,daly city,500,350
john,springfield,800,240
john,richmond,200,80
jane,san jose,300,90
george,albany,200,60
john,centreville,600,150
我一次遍历每行3条记录:
reader = pd.read_csv(input_csv_path, chunksize=3)
for row in reader:
我创建一个pivot_table
并打印出它的索引:
pivot_table_row = row.pivot_table(index=['name', 'location'])
print(pivot_table_row.index)
MultiIndex(levels=[[u'jane', u'john'], [u'daly city', u'fairfax', u'springfield']],
codes=[[0, 1, 1], [0, 1, 2]],
names=[u'name', u'location'])
由于transposition将行转换为列,反之亦然,我希望新的索引被命名为jane
、john
、daly city
和fairfax
,并带有levels=['name', 'location']
。但情况似乎并非如此:
transposed_pivot_table_row = pivot_table_row.T
print(transposed_pivot_table_row.index)
Index([u'customer_count', u'sales'], dtype='object')
为什么索引从MultiIndex
的['name', 'location]
变为Index
的['customer_count', 'sales']
平面
原始的
MultiIndex
整体成为列。转置(customer_count
,sales
)之前中剩余的列成为新的索引,没有名称当您检查
pivot_table_row.index.names
和pivot_table_row.columns.names
属性时,您将看到:如您所见,原始列没有名称开头。一旦发生换位,列就成为索引,因此没有名称。因此在您的示例中,其余的列
customer_count
和sales
共同构成了新索引,没有名称相关问题 更多 >
编程相关推荐