讓我通過注意組合列不是字典來說明此問題。結果數據框在「組合」列中有方括號 - 因此它看起來像數據框中的列表,其格式爲[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
發現以下密切相關的問題,並試圖推導他們,這讓我一半的路,但似乎無法得到完全正確的格式。
- Combine columns in a Pandas DataFrame to a column of lists in a DataFrame
- Merge multiple column values into one column in python pandas
- Convert Dataframe to a Dictionary with List Values
- How to create a dictionary of key : column_name and value : unique values in column in python from a dataframe
我跑這個代碼...和回來 蘋果量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
編輯。請檢查 –
謝謝!在zip中添加單引號,以使list_ = ['\''+ str(b)+'\':\''+ str(a)+'\''(row,col_names.values.tolist ())] – sweetnlow