gpt4 book ai didi

python - Pandas 爆炸功能不适用于字符串列列表

转载 作者:行者123 更新时间:2023-12-04 01:15:35 25 4
gpt4 key购买 nike

要像列到行一样分解列表,我们可以使用 pandas explode()功能。我的 Pandas 版 ' 0.25.3 '
给定的 example为我工作,Stackoverflow.com 的另一个答案按预期工作,但不适用于我的数据集。

    city        nested_city
0 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

最佳答案

您需要确保您的列是列表类型才能使用 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()
要一次分解多个列,您可以执行以下操作:
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()

关于python - Pandas 爆炸功能不适用于字符串列列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63472664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com