【问题标题】:Renaming column names in Pandas Dataframe重命名 Pandas Dataframe 中的列名
【发布时间】:2021-04-24 20:02:26
【问题描述】:

我有下表作为输入:

输入

Column1.ab.gz Column2.ab.gz Column3.ab.gz Column4.ab.gz Column5.ab.gz Column6.ab.gz
1234 0 22 33 5 7
1235 1 2 2 0 234
1236 9 2 82 0 66
1237 0 0 0 0 0
1238 7 11 6 66 1
1239 5 27 5 0 8
1240 0 0 0 0 0
1241 15 0 2 13 5

我想自动重命名不带“ab.gz”的列名,而不是手动重命名列 (data.rename(columns = 'Column1.ab.gz' :'Column1', 'Column2.ab.gz' :'Column2', 'Column3.ab.gz' :'Column3', 'Column4.ab.gz' :'Column4', 'Column5.ab.gz' :'Column5', 'Column6.ab.gz' :'Column6')),因为原始表包含 50 列。 我还想删除所有列值为 0 的行。

输出应如下所示:

输出

Column1 Column2 Column3 Column4 Column5 Column6
1234 0 22 33 5 7
1235 1 2 2 0 234
1236 9 2 82 0 66
1238 7 11 6 66 1
1239 5 27 5 0 8
1241 15 0 2 13 5

我如何在 python 中做到这一点?

提前致谢!

【问题讨论】:

    标签: python pandas numpy rename


    【解决方案1】:

    通过空字符串使用str.replace

    df.columns = df.columns.str.replace('.ab.gz', '')
    print (df)
      Column1  Column2  Column3  Column4  Column5  Column6
    0      aa        0       22       33        5        7
    1      bb        1        2        2        0      234
    2      cc        9        2       82        0       66
    3      ee        0        0        0        0        0
    4      ff        7       11        6       66        1
    5      dd        5       27        5        0        8
    6      aa        0        0        0        0        0
    7      bb       15        0        2       13        5
    

    如果需要第一个.之前的值:

    df.columns = df.columns.str.split('.').str[0]
    

    【讨论】:

      【解决方案2】:

      你可以像这样使用list comprehension

      df.columns=[i.replace('.ab.gz','') for i in df.columns]
      

      【讨论】:

        猜你喜欢
        • 2019-07-21
        • 1970-01-01
        • 2017-03-05
        • 2019-12-01
        • 2013-11-19
        • 2019-09-26
        • 1970-01-01
        相关资源
        最近更新 更多