【问题标题】:Is there anyway to change a dataframe in pandas to have the index in the middle?无论如何要更改熊猫中的数据框以使索引位于中间?
【发布时间】:2020-05-15 20:54:27
【问题描述】:

我有一个数据框显示两个团队相互比较。我想将数据框更改为类似于您在电视上看到的图形。这在 Pandas 中可行吗?

        Shooting  Rebounds  FieldGoal
Team 1  Team1Stat Team1Stat Team1Stat
Team 2  Team2Stat Team2Stat Team2Stat

我希望它是什么样子:

       Team1               Team2
     Team1Stat  Shooting   Team2Stat
     Team1Stat  Rebounds   Team2Stat
     Team1Stat  FieldGoal  Team2Stat

这有可能吗?我在想的是你在 ESPN 上看到的一些东西,它显示了两支球队的并排比较。我知道我可以使用

df1.transpose()

但这只会让我把索引放在左边,我希望把它放在数据框的中间。

【问题讨论】:

    标签: python pandas transpose


    【解决方案1】:

    你不能用索引来做到这一点。如果你真的想在视觉上达到结果, 您可以只创建一个包含 3 个单独列的 DataFrame,例如Team1、类别、Team2

    【讨论】:

      【解决方案2】:

      如果您出于审美目的需要它,这是一种方法:

      import pandas as pd
      
      # for read_clipboard()
      '''
      Shooting    Rebounds    FieldGoal
      Team1   Team1Stat   Team1Stat   Team1Stat
      Team2   Team2Stat   Team2Stat   Team2Stat
      '''
      
      df = pd.read_clipboard(sep='\t+')
      
      df_new = df.T.reset_index()
      df_new = df_new[['Team1', 'index', 'Team2']]
      df_new.columns = ['Team1', '', 'Team2']
      
      print(df_new)
      

      输出:

             Team1                 Team2
      0  Team1Stat   Shooting  Team2Stat
      1  Team1Stat   Rebounds  Team2Stat
      2  Team1Stat  FieldGoal  Team2Stat
      

      【讨论】:

        猜你喜欢
        • 2020-06-24
        • 2020-04-01
        • 2017-03-18
        • 2018-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-18
        相关资源
        最近更新 更多