Pandas的explode函数对于包含字符串列表的列无法正常工作

9
为了将列表列转换为行,我们可以使用pandas的explode()函数。我的pandas版本为'0.25.3'。
给定的示例对我有效,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

请检查 nested_city 是列表还是字符串? - BENY
1:你是否遇到了任何错误?如果是这样,你可能需要检查pandas的版本。 2:检查它们是否是实际的列表(test_data['nested_city'].apply(type)),还是只是列表的字符串表示形式。如果是后者,则执行test_data['nested_city'].apply(ast.literal_eval).explode() - anky
type(test_data['nested_city']) 返回的是 pandas.core.series.Series。 - A l w a y s S u n n y
2
@AlwaysSunny 这就是为什么 <class 'str'> 不是列表类型,而是用于列表类型的explode - BENY
1
我建议你花些时间了解各种方法支持的Python数据类型,对于你最后的查询,你需要使用df.join循环,请查看文档。我会把它留给你作为家庭作业 :) - anky
显示剩余4条评论
1个回答

22
你需要确保你的列是列表类型才能使用 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()

如果您从literal_eval获得异常,请确保您的列是列表的字符串表示形式- test_data ['nested_city'] = test_data ['nested_city'] .fillna({i:[] for i in test_data.index})和`test_data ['nested_city'] =' [ '+ test_data ['nested_city'] .astype(str)+' ]' - gary69

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接