【问题标题】:How to reverse .astype(str) in pandas dataframe?如何在熊猫数据框中反转 .astype(str)?
【发布时间】:2019-08-02 12:35:32
【问题描述】:

我必须删除数据框中包含列表值的重复行。

所以我用了

pd_data['douban_info_string'] = pd_data['douban_info'].astype(str)

'douban_info_string' 有列表值。

但是现在我需要这个列表来与另一个数据框的列表进行比较。但是现在列表已更改为字符串,我收到此错误

TypeError: unhashable type: 'list'

【问题讨论】:

  • 您可以使用import ast pd_data['douban_info'].apply(ast.literal_eval) 将其转回列表??
  • @anky_91 没用 :(

标签: python python-3.x pandas dataframe


【解决方案1】:

使用pandas.eval:

df = pd.DataFrame({'info':[[1,2,3], [4,5,6]]})

df['info_str']=df['info'].astype(str)
df['info_str'][0]
# '[1, 2, 3]'

df['info_str'].apply(pd.eval)[0]
# [1,2,3]

【讨论】:

  • 我收到此错误 ValueError: unknown type str224
  • @Miffy 我相信您的专栏包含非列表式 strs,例如“str224”。
  • 我的专栏有嵌套列表,并且在转换它的列表字符串后
  • @Miffy 嵌套列表的元素是什么?它们是否只包含ints?
  • 不,它们包含字符串
【解决方案2】:

在 if 语句中使用 apply:

df = pd.DataFrame({'info':[[1,2,3], [4,5,6], 'str224']})
df['info_str'] = df['info'].astype(str)
print(df['info_str'][0])
print(type(df['info_str'][0]))
print(df['info_str'].apply(lambda x: x if x in df['info'].tolist() else pd.eval(x))[0])
print(type(df['info_str'].apply(lambda x: x if x in df['info'].tolist() else pd.eval(x))[0]))

输出:

[1, 2, 3]
<class 'str'>
[1 2 3]
<class 'numpy.ndarray'>

【讨论】:

    【解决方案3】:

    试试这个

    pd_data['douban_info_string_list'] = pd_data['douban_info_string'].map(lambda x: x.replace('[', '').replace(']', '').split(','))
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 2020-02-24
      • 2021-05-27
      • 2017-05-24
      • 2023-03-13
      • 2013-12-24
      • 2018-11-19
      相关资源
      最近更新 更多