Python 为什么在我的数据中调用转置会切换行';从多重索引到平坦索引的s索引?

Python 为什么在我的数据中调用转置会切换行';从多重索引到平坦索引的s索引?,python,pandas,Python,Pandas,我有一个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,看起来像这样:

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\u表
,并打印出其索引:

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
,级别为
级别=['name','location']
。情况似乎并非如此:

    transposed_pivot_table_row = pivot_table_row.T
    print(transposed_pivot_table_row.index)

Index([u'customer_count', u'sales'], dtype='object')

为什么索引从
[“名称”、“位置]
多索引
变为
[“客户计数”、“销售”]
的扁平
索引?

原始的
多索引
整体成为列。转置之前的剩余列(
customer\u count
sales
)成为新索引,没有名称

检查
pivot\u table\u row.index.names
pivot\u table\u row.columns.names
属性时,您会看到这一点:

    pivot_table_row = df.pivot_table(index=['name', 'location'])
    print(pivot_table_row.index.names)
    ['name', 'location']

    print(pivot_table_row.columns.names)
    [None]

    pivot_table_row = df.pivot_table(index=['name', 'location']).T
    print(pivot_table_row.index.names)
    [None]

    print(pivot_table_row.columns.names)
    ['name', 'location']

如您所见,原始列没有名称开头。一旦发生换位,列就成为索引,因此没有名称。因此,在您的示例中,剩余的列
customer\u count
sales
共同构成了新的索引,没有名称。

虽然这表明索引名称变成了列名,但它并不能回答为什么旧的
多索引
变成了平面
索引。为什么一开始就以某种方式设置这些级别?为什么在转换位置之后,索引中不再有级别?@CJVirtucio-因为列在索引中更改。所以如果在索引中使用多索引,那么在转置多索引之后columns@CJVirtucio-如果列中没有多索引,那么在转置之后,在indexOk中没有多索引,我想我知道你想说什么了。因此原始的
多索引
整体成为列。转置之前的剩余列(
customer\u count
sales
)成为新索引,没有名称。对吗?@CJVirtucio-没错;)