使用 lambda 以字符串开头时替换 DataFrame 列中的值 [英] Replace values in DataFrame column when they start with string using lambda
本文介绍了使用 lambda 以字符串开头时替换 DataFrame 列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框:
将pandas导入为pd将 numpy 导入为 npx = {'值':['测试','XXX123','XXX456','测试']}df = pd.DataFrame(x)
我想使用 lambda 用 np.nan 替换以 XXX 开头的值.
我尝试了很多关于替换、应用和映射的事情,我能做的最好的是 False, True, True, False.
以下有效,但我想知道更好的方法,我认为应用、替换和 lambda 可能是更好的方法.
df.Value.loc[df.Value.str.startswith('XXX', na=False)] = np.nan
解决方案
使用
I have a DataFrame:
import pandas as pd
import numpy as np
x = {'Value': ['Test', 'XXX123', 'XXX456', 'Test']}
df = pd.DataFrame(x)
I want to replace the values starting with XXX with np.nan using lambda.
I have tried many things with replace, apply and map and the best I have been able to do is False, True, True, False.
The below works, but I would like to know a better way to do it and I think the apply, replace and a lambda is probably a better way to do it.
df.Value.loc[df.Value.str.startswith('XXX', na=False)] = np.nan
解决方案
use the apply method
In [80]: x = {'Value': ['Test', 'XXX123', 'XXX456', 'Test']}
In [81]: df = pd.DataFrame(x)
In [82]: df.Value.apply(lambda x: np.nan if x.startswith('XXX') else x)
Out[82]:
0 Test
1 NaN
2 NaN
3 Test
Name: Value, dtype: object
Performance Comparision of apply, where, loc
这篇关于使用 lambda 以字符串开头时替换 DataFrame 列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文