我有一個這樣的資料結構:
lst = ['name, age, sex, height, weight',
'underweight,overweight,normal',
'David, 22, M, 185, -,-,78',
'Lily, 18, F, 165,-,75,-',
..............................]
權重被歸類為另外三列(串列中的第二行)。如何將其寫入熊貓資料框。
我所做的是使用以下方法將串列撰寫為資料框:
pd.DataFrame(lst)
但這不是完整的解決方案,它有更復雜的邏輯。
請幫幫我
uj5u.com熱心網友回復:
您期望的輸出并不完全清楚,但您可以使用串列理解來預處理您的資料:
lst2 = [list(map(str.strip, e.split(','))) for e in lst] # split on commas
pd.DataFrame(lst2[2:], columns=lst2[0][:-1] lst2[1]) # use first 2 item to build header
# rest is data
輸出:
name age sex height underweight overweight normal
0 David 22 M 185 - - 78
1 Lily 18 F 165 - 75 -
多索引
雖然可行,但我不建議這樣做,使用它會困難得多:
lst2 = [list(map(str.strip, e.split(','))) for e in lst]
cols = pd.MultiIndex.from_arrays([lst2[0][:-1] [lst2[0][-1]]*3,
['']*4 lst2[1]])
pd.DataFrame(lst2[2:], columns=cols)
輸出:
name age sex height weight
underweight overweight normal
0 David 22 M 185 - - 78
1 Lily 18 F 165 - 75 -
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366357.html
