【问题标题】:Categories columns in second row to the first row in DataFrame Pandas?DataFrame Pandas中第二行到第一行的分类列?
【发布时间】:2017-09-27 18:00:39
【问题描述】:

我有这个数据库:

Unnamed=0          2001 2002 2003

General             456  567  543
Cleaning            234  234  344

转置数据后,我得到了Jupyter Notebook第二行的变量:

df = df.T.rename_axis('Date').reset_index()
df
   Date       1         2
1           General  Cleaning
2  2001      456       234
3  2002      567       234
4  2003      543       344

如何将它们放在 DataFrame 的第一行,以便对值进行分组和操作?

   Date     General  Cleaning
1  2001      456       234
2  2002      567       234
3  2003      543       344

【问题讨论】:

    标签: python pandas numpy jupyter-notebook


    【解决方案1】:

    您与上面显示的尝试很接近。相反,reset the index 将日期从索引移动到第一列,然后 rename 将该日期列从 index 移动到 Date

    df = df.T.reset_index().rename(columns={'index':'Date'})
    df
    

    输出:

       Date General Cleaning
    0  2001     456      234
    1  2002     567      234
    2  2003     543      344
    

    【讨论】:

    • 感谢您的帮助。
    【解决方案2】:

    您可以简单地删除第 1 行并重命名列。

    df.drop(1, axis=0, inplace=True)
    df.columns= ['Date', 'General', 'Cleaning']
    

    【讨论】:

      【解决方案3】:

      假设这个df:

      df = pd.DataFrame(data=[[2001,2002,2003],[456,567,543],[234,234,344]],index=[0,'General','Cleaning'])
      

      去做吧:

      df = df.T.copy().rename(columns={0:'Date'})
      

      【讨论】:

        猜你喜欢
        • 2019-02-27
        • 2021-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-13
        • 2015-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多