簡體   English   中英

如何在pandas數據幀中反轉.astype(str)?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM