我有一个(n,m)维的dataframe,它的列是"dtype对象“,它有不同长度的字符串。df如下所示:
col1 col2 col3 col4 ... colm
|---------------------------------------------
row1| str1,1 str1,2 str1,3 str1,4 ... str1,m
row2| str2,1 str2,2 str2,3 str2,4 ... str2,m
. | . . . . ... .
. | . . . . ... .
. | . . . . ... .
rown| strn,1 strn,2 strn,3 strn,4 ... strn,m我希望将特定的字符串替换为NaN的字符串,条件是字符串的长度必须小于10,但仅限于某些列。
下面是我的代码:
column_list = ['col1','col3']
df.loc[:,column_list] = df.apply(lambda x: x.str.replace(x,np.NaN) if len(x) < 10 else x)代码运行时没有错误,但不幸的是,实际上并没有对这些列中的值做任何操作。我认为我的问题与以下部分有关:
x.str.replace(x,np.NaN) 我不认为"x“应该在”替换“函数中。
感谢你的帮助。
谢谢
发布于 2019-03-07 05:57:35
在通过str.len获得字符串长度后,只需使用mask即可
s=df.apply(lambda x : x.str.len())<10
df.loc[:,column_list]=df.loc[:,column_list].mask(s)https://stackoverflow.com/questions/55032664
复制相似问题