[英]How to reverse .astype(str) in pandas dataframe?
我不得不删除数据框中包含列表值的重复行。
所以我用过
pd_data['douban_info_string'] = pd_data['douban_info'].astype(str)
其中'douban_info_string'有列表值。
但现在我需要这个列表与另一个数据框的列表进行比较。 但是列表现在变成了字符串,我收到了这个错误
TypeError: unhashable type: 'list'
使用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]
使用带有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'>
尝试这个
pd_data['douban_info_string_list'] = pd_data['douban_info_string'].map(lambda x: x.replace('[', '').replace(']', '').split(','))
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.