【问题标题】:Read csv and retain index names读取 csv 并保留索引名称
【发布时间】:2021-09-08 20:36:15
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x pandas indexing


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      • 2016-06-10
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多