python - 如何将 pandas DataFrame 中的列表列更改为常规列表?

标签 python pandas numpy dataframe sublist

我有一个 Pandas DataFrame。它的一列是列表的列表。

enter image description here

执行以下操作的最佳方法是什么:

  1. 用“other”一词填充 list_of_lists 列中的空列表吗? 例如[] 应该变成 ['other']
  2. 将 list_of_lists 列更改为常规分类列表?它最终应该看起来像这样......

enter image description here

最佳答案

您不应该在 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/

相关文章:

python - 重新排列列表中的字母

python - MySQL自增两部分主键

python - BeautifulSoup 抓取新闻文章

python - Panda dataframe column cut - 在均值附近更频繁地添加更多 bin

python - numpy 是否提供广义内积?

python - 试图理解 python,为什么这个函数不起作用? [添加公式]

python - 如何在 python 中生成声音输出..?

python - 在 Python 中从具有多个多元时间序列的数据帧创建数组数组

python - 基于另一个数组对一个数组进行直方图

python - 使用 PyCapture2 读取 MONO 16 位图像