【问题标题】:Python-Pandas convert columns into rowsPython-Pandas 将列转换为行
【发布时间】:2020-05-09 09:08:23
【问题描述】:

我的 excel 数据库有一些按国家/地区多年的信息。问题是每年都有不同的列标题。例如:

Country      Indicator   1950    1951    1952
Australia       x         10      27     20
Australia       y          7      11      8
Australia       z         40      32     37

我想将每个指标转换为列标题并按年份制作一列。像这样:

Country         year          x       y     z
Australia       1950         10       7     40
Australia       1951         27      11     32
Australia       1952         20       8     37

而且我不知道列中有多少个国家。年 = 1950 年到 2019 年

【问题讨论】:

  • 当您说数据库时,您是指您使用的是 SQL 数据库还是您说的是 Excel 表格?
  • 一张excel表格。

标签: python pandas


【解决方案1】:

我们可以使用stackunstack 进行格式化

df.set_index(['Country','Indicator']).stack().unstack(level=1).reset_index()
Indicator    Country level_1   x   y   z
0          Australia    1950  10   7  40
1          Australia    1951  27  11  32
2          Australia    1952  20   8  37

【讨论】:

    【解决方案2】:

    这只是一个探索......@Yoben 的解决方案是通过 Pandas 实现它的正确方法......我只是看到还有其他可能性:

    #create a dictionary of the years
    years = {'Year' : df.filter(regex='\d').columns}
    
    #get the data for the years column
    year_data = df.filter(regex='\d').to_numpy()
    
    #create a dictionary from the indicator and years columns pairing
    reshaped = dict(zip(df.Indicator,year_data))
    reshaped.update(years)
    
    #create a new dataframe
    pd.DataFrame(reshaped,index=df.Country)
    
                x   y   z   Year
    Country             
    Australia   10  7   40  1950
    Australia   27  11  32  1951
    Australia   20  8   37  1952
    

    您永远不必这样做,因为您可以轻松地在数据框中工作,而无需创建新数据框。您唯一可以考虑的是速度。除此之外,只是一些值得探索的东西

    【讨论】:

      【解决方案3】:

      这不是你要找的,但如果你的数据帧是变量df,你可以使用转置方法来反转数据帧。

      In [7]: df                                                                                           
      Out[7]: 
         col1   col2  col3
      0     1   True    10
      1     2  False    10
      2     3  False   100
      3     4   True   100
      

      转置

      In [8]: df.T                                                                                         
      Out[8]: 
               0      1      2     3
      col1     1      2      3     4
      col2  True  False  False  True
      col3    10     10    100   100
      

      我认为您有一个多索引数据框,因此您可能需要查看相关文档。

      【讨论】:

        猜你喜欢
        • 2021-11-09
        • 1970-01-01
        • 2021-09-12
        • 1970-01-01
        • 1970-01-01
        • 2017-10-25
        • 2013-06-22
        • 2023-03-02
        • 1970-01-01
        相关资源
        最近更新 更多