2017-08-30 81 views
1

在下面一行中,我將三個系列(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]] 

回答

0

我想你需要創建的常量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 
+0

我遇到的問題是,數據幀有時間戳,但之前的系列是字符串。所以,我必須將列表轉換爲str,然後添加。什麼是最好的方法? –

+0

我認爲simpliest是'totalheldprofit.columns [0:3] .astype(str).tolist()' – jezrael

+0

pnlsummary.columns = [totalheldmw.name [0],totalcost.name [0],totalsellprofit.name [0 ] + totalheldprofit.columns [0:3] .astype(str).tolist()] TypeError:不能將'list'對象隱式轉換爲str。思考? –