【问题标题】:Renaming column of one dataframe by extracting from combination of series and dataframe column names通过从系列和数据框列名的组合中提取来重命名一个数据框的列
【发布时间】:2018-02-07 16:44:27
【问题描述】:

在下面的行中,我从三个系列(totalheldmw、totalcost 和 totalsellprofit)和一个数据框(totalheldprofit)的列名中重命名了 pnlsummary 数据框的列。

我遇到的困难是遍历数据框的列名。我已经手动分配了名称,如下所示。我想有一种有效的方法可以遍历数据框的列名。请指教。

pnlsummary.columns =
[totalheldmw.name[0],totalcost.name[0],totalsellprofit.name[0],
totalheldprofit.columns[0],totalheldprofit.columns[1],
totalheldprofit.columns[2],totalheldprofit.columns[3]]

【问题讨论】:

    标签: pandas dataframe rename multiple-columns


    【解决方案1】:

    我认为您需要通过常量创建list,然后添加转换为list 的列名:

    pnlsummary.columns = [totalheldmw.name[0],totalcost.name[0],totalsellprofit.name[0]] +
                          totalheldprofit.columns[0:3].astype(str).tolist()
    

    示例:

    df = pd.DataFrame({'A':list('abcdef'),
                       'B':[4,5,4,5,5,4],
                       'C':[7,8,9,4,2,3],
                       'D':[1,3,5,7,1,0],
                       'E':[5,3,6,9,2,4],
                       'F':list('aaabbb')})
    
    print (df)
       A  B  C  D  E  F
    0  a  4  7  1  5  a
    1  b  5  8  3  3  a
    2  c  4  9  5  6  a
    3  d  5  4  7  9  b
    4  e  5  2  1  2  b
    5  f  4  3  0  4  b
    
    df.columns = ['a','s','d'] + df.columns[0:3].tolist()
    print (df)
       a  s  d  A  B  C
    0  a  4  7  1  5  a
    1  b  5  8  3  3  a
    2  c  4  9  5  6  a
    3  d  5  4  7  9  b
    4  e  5  2  1  2  b
    5  f  4  3  0  4  b
    

    【讨论】:

    • 我遇到的问题是数据帧有时间戳,但之前的系列是字符串。所以,我必须将列表转换为 str 然后添加。最好的方法是什么?
    • 我觉得最简单的就是totalheldprofit.columns[0:3].astype(str).tolist()
    • pnlsummary.columns=[totalheldmw.name[0],totalcost.name[0],totalsellprofit.name[0] + totalheldprofit.columns[0:3].astype(str).tolist( )] 类型错误:无法将“列表”对象隐式转换为 str。想法?
    • 你错了[],需要pnlsummary.columns=[totalheldmw.name[0],totalcost.name[0],to‌​talsellprofit.name[0‌​] ] + totalheldprofit.columns[0:3].astype(str).tolist()
    • 工作。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 2021-11-15
    • 2018-08-16
    • 1970-01-01
    相关资源
    最近更新 更多