如何将数据帧中的列表列更改为常规列表?

2024-04-19 13:02:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框。其中一列是列表列表。你知道吗

enter image description here

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

  1. 用“其他”一词填充“列表”列中的空列表?e、 g.[]应该变成['other']
  2. 将列表列的列表更改为常规的分类列表?结果应该是这样的。。。你知道吗

enter image description here


Tags: 数据方法列表分类常规other
3条回答

IIUC公司

df.A=[x if x  else ['other']  for x in df.A  ]
df
Out[298]: 
          A
0   [other]
1   [steel]
2   [steel]
3   [other]
4  [tarmac]
5   [other]

有很多原因不应该在对象中使用列表。您的第一个调用端口应该是提取字符串并将序列转换为分类数据:

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是不可散列的。你知道吗

另一个窍门:

>>> df
          A
0        []
1   [steel]
2   [steel]
3        []
4  [tarmac]
5        []

>>> df.A.apply(lambda y: "[other]"  if len(y)==0 else y)
0     [other]
1     [steel]
2     [steel]
3     [other]
4    [tarmac]
5     [other]
Name: A, dtype: object

或:

  >>> df['A'].apply(lambda x: x if x else ['other'])
0     [other]
1     [steel]
2     [steel]
3     [other]
4    [tarmac]
5     [other]
Name: A, dtype: object

相关问题 更多 >