读取 csv 并保留索引名称

时间:2021-06-25 12:41:34

标签: python python-3.x pandas indexing

我有一个数据框需要保存在下面的结构中。

pd.read_csv(filepath, header=[0,1])
  One             two           three      four    
  country        date           apple     banana
0 UK             2015-01-01       0         4
1 US             2020-01-03      10         5

如何将前 2 行和 2 列作为索引并保留名称?

pd.read_csv(filepath, header=[0,1], index_col=[0,1])

       One            three   four       
      country        apple    banana
UK   2015-01-01         0        4
US   2020-01-03        10        5

预期输出是前 2 行和前 2 列作为具有适当名称的索引

One             two           three      four    
country        date           apple     banana
UK             2015-01-01         0         4
US             2020-01-03        10         5

1 个答案:

答案 0 :(得分:0)

不,你不能。最相似的数据框将是:

df = pd.read_csv(filepath, header=[0,1])
df.set_index(df.columns[0])

                two         three   four
                date        apple   banana
(One, country)          
UK              2015-01-01  0       4
US              2020-01-03  10      5
相关问题