要從列到行分解列表,我們可以使用 pandas?explode()函數(shù)。我的熊貓'版本'?0.25.3?'給定的示例對我有用,Stackoverflow.com 的另一個答案按預(yù)期工作,但不適用于我的數(shù)據(jù)集。? ? city? ? ? ? nested_city0? ?soto? ? ? ? ['Soto']1? ?tera-kora? ?['Daniel']2? ?jan-thiel? ?['Jan Thiel']3? ?westpunt? ? ['Westpunt']4? ?nieuwpoort? ['Nieuwpoort', 'Santa Barbara Plantation']我試過的:test_data['nested_city'].explode()和test_data.set_index(['nested_city']).apply(pd.Series.explode).reset_index()輸出0? ? ['Soto']? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??1? ? ['Daniel']? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??2? ? ['Jan Thiel']? ? ? ? ? ? ? ? ? ? ? ? ? ? ?3? ? ['Westpunt']? ? ? ? ? ? ? ? ? ? ? ? ? ? ??4? ? ['Nieuwpoort', 'Santa Barbara Plantation']Name: neighbors, dtype: object
1 回答

吃雞游戲
TA貢獻(xiàn)1829條經(jīng)驗 獲得超7個贊
您需要確保您的列是列表類型才能使用 pandas' explode()。這是一個有效的解決方案:
from ast import literal_eval
test_data['nested_city'] = test_data['nested_city'].apply(literal_eval) #convert to list type
test_data['nested_city'].explode()
要一次分解多個列,您可以執(zhí)行以下操作:
not_list_cols = [col for col in test_data.columns if col not in ['col1', 'col2']] #list of columns you are not exploding (assume col1 and col2 are being exploded)
test_data = test_data.set_index(not_list_cols).apply(pd.Series.explode).reset_index()
添加回答
舉報
0/150
提交
取消