我正在嘗試從 Pandas 資料框創建一種嵌套串列。
我有這個資料框:
id1 Name1 ids1 Name2 ids2 ID col1 Goal col2 col3
0 ab-85643 aasd1 234,34,11223,345,345_2 vaasd1 2234,354,223,35,3435 G-0001 1 NaN 3 1
1 ab-85644 aasd2 2343,355,121,34 G-0002 2 56.0000 4 22
2 ab-8564312 aabsd1 24 , 23 ,244 ,2421 ,567 ,789 G-00023 3 NaN 32 33
3 ab-8564314 aabsd2 87 ,35 ,67_1 averabsd 387 ,355 ,667_1 G-01034 4 89.0000 43 44
#Here is the above data frame and you can convert it again to pandas using the below command
df.to_dict()
dic = {'id1 ': {0: ab-85643, 1: ab-85644, 2: ab-8564312, 3: ab-8564314},
'Name1': {0: 'aasd1 ', 1: 'aasd2 ', 2: 'aabsd1', 3: 'aabsd2'},
'ids1 ': {0: '234,34,11223,345,345_2 ',
1: '2343,355,121,34 ',
2: '24 , 23 ,244 ,2421 ,567 ,789',
3: '87 ,35 ,67_1 '},
'Name2': {0: 'vaasd1 ', 1: ' ', 2: ' ', 3: 'averabsd'},
'ids2': {0: '2234,354,223,35,3435',
1: ' ',
2: ' ',
3: ' 387 ,355 ,667_1 '},
'ID': {0: 'G-0001 ', 1: 'G-0002 ', 2: 'G-00023', 3: 'G-01034'},
'col1': {0: 1, 1: 2, 2: 3, 3: 4},
'Goal ': {0: ' NaN ', 1: 56, 2: ' NaN ', 3: 89},
'col2': {0: 3, 1: 4, 2: 32, 3: 43},
'col3': {0: 1, 1: 22, 2: 33, 3: 44}}
pd.DataFrame.from_dict(dic)
所以我想使用上面的資料框使用 'id1' 列以及 'Name1' 和 'Name2' 列創建一種嵌套串列。例如,如果我們考慮第一行, id1 應該在一個串列中(['ab-85643'])而 ' Name1'和 'Name2' 應該是另一個串列(['aasd1','vaasd1'])。然后對于第一行,id1 串列和 'Name1' 和 'Name2' 串列應該在同一個串列中([['aasd1','vaasd1'],['ab-85643']])。某些行沒有“Name”或“Name2”。這應該需要對所有行進行,最終串列應該與下面的串列一樣。
collection = [[ ['aasd1','vaasd1'],['ab-85643'] ],[ ['aasd2'],['ab-85644'] ],[ ['aabsd1'],['ab-8564312'] ],[ ['aabsd2','averabsd'],['ab-8564314'] ]]
是否可以使用python創建它?
有人可以給我一個想法嗎?
任何事情都值得贊賞。提前致謝!
uj5u.com熱心網友回復:
如果將自定義函式應用于相關列會更容易:
def get_collections(row):
first = row[:2].str.strip()
return [first[first!=''].tolist(), [row[2]]]
out = df[['Name1','Name2','id1']].apply(get_collections, axis=1).tolist()
輸出:
[[['aasd1', 'vaasd1'], ['ab-85643']],
[['aasd2'], ['ab-85644']],
[['aabsd1'], ['ab-8564312']],
[['aabsd2', 'averabsd'], ['ab-8564314']]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398302.html
