我有一个 Pandas DataFrame。它的一列是列表的列表。
执行以下操作的最佳方法是什么:
- 用“other”一词填充 list_of_lists 列中的空列表吗? 例如[] 应该变成 ['other']
- 将 list_of_lists 列更改为常规分类列表?它最终应该看起来像这样......
最佳答案
您不应该在 Pandas 系列对象中使用列表的原因有很多。您的第一个调用应该是提取字符串并将系列转换为分类数据:
df = pd.DataFrame({'A': [[], ['steel'], ['steel'], [], ['tarmac'], []]})
df['A'] = df['A'].str[0].fillna('other').astype('category')
print(df)
A
0 other
1 steel
2 steel
3 other
4 tarmac
5 other
<小时/>
如果您坚持通过 Python 级循环使用低效且不可向量化的操作,那么您可以通过这种方式实现您想要的:
df['A'] = df['A'].str[0].fillna('other').apply(lambda x: [x])
print(df)
A
0 [other]
1 [steel]
2 [steel]
3 [other]
4 [tarmac]
5 [other]
此时,分类数据不是一个选项,因为分类数据不支持一系列列表,因为 list
不可散列。
关于python - 如何将 pandas DataFrame 中的列表列更改为常规列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53451459/