我有以下資料框,其中包含一列嵌套元組:
index nested_tuples
1 (('a',(1,0)),('b',(2,0)),('c',(3,0)))
2 (('a',(5,0)),('d',(6,0)),('e',(7,0)),('f',(8,0)))
3 (('c',(4,0)),('d',(5,0)),('g',(6,0)),('h',(7,0)))
我正在嘗試解包元組以獲取以下資料框:
index a b c d e f g h
1 1 2 3
2 5 6 7 8
3 4 5 6 7
即對于每個元組( char, (num1, num2) ),我希望 char 是一列,而 num1 是條目。我最初嘗試了各種方法,to_list()但由于迷你元組的數量和其中的字符不同,我無法在不丟失資訊的情況下使用它,最終我能想到的唯一解決方案是:
for index, row in df.iterrows():
tuples = row['nested_tuples']
if not tuples:
continue
for mini_tuple in tuples:
df.loc[index, mini_tuple[0]] = mini_tuple[1][0]
但是,對于嵌套元組很長且 df 非常大的實際資料框,iterrows速度非常慢。有沒有更好的矢量化方法來做到這一點?
uj5u.com熱心網友回復:
在構建 DataFrame 之前,在 vanilla Python 中清理資料可能更有效:
out = pd.DataFrame([{k:v[0] for k,v in tpl} for tpl in df['nested_tuples'].tolist()])
更簡潔一點:
out = pd.DataFrame(map(dict, df['nested_tuples'])).stack().str[0].unstack()
另一個選項使用apply:
out = pd.DataFrame(df['nested_tuples'].apply(lambda x: {k:v[0] for k,v in x}).tolist())
輸出:
a b c d e f g h
0 1.0 2.0 3.0 NaN NaN NaN NaN NaN
1 5.0 NaN NaN 6.0 7.0 8.0 NaN NaN
2 NaN NaN 4.0 5.0 NaN NaN 6.0 7.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/461321.html
標籤:Python python-3.x 熊猫 数据框 元组
上一篇:將嵌套JSON轉換為Pandas資料框(帶有JSON示例)
下一篇:根據某些條件將df轉換為字典
