如何从Pandas数据框中的列表中删除值? [英] How to remove a value from a list in a Pandas dataframe?
本文介绍了如何从Pandas数据框中的列表中删除值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个数据框:
[in] testing_df =pd.DataFrame(test_array,columns=['transaction_id','product_id'])
# Split the product_id's for the testing data
testing_df.set_index(['transaction_id'],inplace=True)
testing_df['product_id'] = testing_df['product_id'].apply(lambda row: row.split(','))
[out] product_id
transaction_id
001 [P01]
002 [P01, P02]
003 [P01, P02, P09]
004 [P01, P03]
005 [P01, P03, P05]
006 [P01, P03, P07]
007 [P01, P03, P08]
008 [P01, P04]
009 [P01, P04, P05]
010 [P01, P04, P08]
现在如何从结果中删除"P04"和"P08"?
How can I now remove 'P04' and 'P08' from the results?
我尝试过:
# Remove P04 and P08 from consideration
testing_df['product_id'] = testing_df['product_id'].map(lambda x: x.strip('P04'))
testing_df['product_id'].replace(regex=True,inplace=True,to_replace=r'P04,',value=r'')
但是,这两个选项似乎都不起作用.
However, neither option seems to work.
数据类型为:
[in] print(testing_df.dtypes)
[out] product_id object
dtype: object
[in] print(testing_df['product_id'].dtypes)
[out] object
推荐答案
将要删除的所有元素存储在列表中.
store all your elements to be removed in a list.
remove_results = ['P04','P08']
for k in range(len(testing_df['product_id'])):
for r in remove_results:
if r in testing_df['product_id'][k]:
testing_df['product_id][k].remove(r)
这篇关于如何从Pandas数据框中的列表中删除值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文