如何在数据帧中反转.astype(str)?

2024-05-29 04:45:37 发布

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

我必须删除数据帧中的重复行,其中包含列表值。你知道吗

所以我用

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

其中“豆瓣信息字符串”具有列表值。你知道吗

但现在我需要这个列表和另一个数据帧的列表进行比较。但是现在列表变成了字符串,我得到了这个错误

TypeError: unhashable type: 'list'

Tags: 数据字符串info信息列表datastring错误
3条回答

试试这个

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

希望有帮助。你知道吗

使用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]

apply与if语句一起使用:

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'>

相关问题 更多 >

    热门问题