2017-08-14 367 views
2

讓我通過注意組合列不是字典來說明此問題。結果數據框在「組合」列中有方括號 - 因此它看起來像數據框中的列表,其格式爲[key1:value1,key2:value2等]。在Python中使用[key:value]組合將多個列合併到一個列表中

我想我的數據幀從這個轉換:

import pandas as pd 
test = pd.DataFrame({'apples':['red','green','yellow'], 'quantity': 
[1,2,3],'tasteFactor':['yum','yum','yuck']}) 

    apples quantity tasteFactor 
0  red   1   yum 
1 green   2   yum 
2 yellow   3  yuck 

爲此格式,這是與價值觀每一行按鍵組合成一個新列:

apples quantity tasteFactor combined 
0  red   1   yum ['apples':'red','quantity':'1','tastefactor':'yum'] 
1 green   2   yum ['apples':'green','quantity':'2','tastefactor':'yum'] 
2 yellow   3  yuck ['apples':'yellow','quantity':'3','tastefactor':'yuck'] 

試圖把數據框每行放入一個字典中,但是被卡住的轉換成列表。

test['combined'] = test.to_dict(orient='records') 

生成的新列不需要是實際的列表類型。它可能是一個字符串。

以前在這裏問過這個問題,但想澄清這個問題的標題問題。 How to Create a List from a Dictionary within a DataFrame in Python

發現以下密切相關的問題,並試圖推導他們,這讓我一半的路,但似乎無法得到完全正確的格式。

回答

1

您可以通過使用熊貓dataframes的應用方法做

import pandas as pd 
df = pd.DataFrame({'apples':['red','green','yellow'], 'quantity': 
[1,2,3],'tasteFactor':['yum','yum','yuck']}) 

col_names = df.columns 

def func(row): 
    global col_names 
    list_ = [str(b)+':'+str(a) for a,b in zip(row,col_names.values.tolist())] 
    return list_ 

x = list(map(func, df.values.tolist())) 
df.loc[:,'combined'] = pd.Series(x) 
# df 
# apples quantity tasteFactor          combined 
# 0  red   1   yum  [apples:red, quantity:1, tasteFactor:yum] 
# 1 green   2   yum [apples:green, quantity:2, tasteFactor:yum] 
# 2 yellow   3  yuck [apples:yellow, quantity:3, tasteFactor:yuck] 
+0

我跑這個代碼...和回來 蘋果量tasteFactor組合 0紅1成蔭(A,P,P,L,E,S) 1綠色2 yum(q,u,a,n,t,i,t,y) 2黃色3 yuck(t,a,s,t,e,F,a,c,t,o,r) – sweetnlow

+0

編輯。請檢查 –

+0

謝謝!在zip中添加單引號,以使list_ = ['\''+ str(b)+'\':\''+ str(a)+'\''(row,col_names.values.tolist ())] – sweetnlow

0

正如您所提到的生成的新列不需要是實際的列表類型。

di=test.T.to_dict() 
test['Mapper']=test.index 
test.Mapper.map(di) 
test.assign(combined=test.Mapper.map(di)).drop('Mapper',1) 


Out[493]: 
    apples quantity tasteFactor           combined 
0  red   1   yum {'apples': 'red', 'quantity': 1, 'tasteFactor'... 
1 green   2   yum {'apples': 'green', 'quantity': 2, 'tasteFacto... 
2 yellow   3  yuck {'apples': 'yellow', 'quantity': 3, 'tasteFact... 

編輯:

di=test.T.to_dict() 
test['Mapper']=test.index 
test.Mapper.map(di) 
test=test.assign(combined=test.Mapper.map(di).astype(str)).drop('Mapper',1) 
test=test.combined.str.replace('{','[').str.replace('}',']') 


test.combined[0] 
Out[511]: "['apples': 'red', 'quantity': 1, 'tasteFactor': 'yum']" 
+0

是的,但是正在尋找方括號格式,它可能是一個字符串類型。 – sweetnlow

+0

@sweetnlow給我一秒 – Wen

+0

@sweetnlow編輯,只需使用'str.replace' – Wen

相關問題