我有一个与此类似的csv文件,但其中包含约155,000行,其中包含1910-2010年的年份以及83个不同的站点ID:
station_id year month element 1 2 3 4 5 6
216565 2008 7 SNOW 0TT 0 0 0 0 0
216565 2008 8 SNOW 0 0T 0 0 0 0
216565 2008 9 SNOW 0 0 0 0 0 0
我想用NaN替换任何具有数字,然后一个字母或一个数字然后两个字母的模式的值。
我想要的输出是:
station_id year month element 1 2 3 4 5 6
216565 2008 7 SNOW NaN 0 0 0 0 0
216565 2008 8 SNOW 0 NaN 0 0 0 0
216565 2008 9 SNOW 0 0 0 0 0 0
我尝试使用:
replace=df.replace([r'[0-9] [A-Z]'], ['NA']) replace2=replace.replace([r'[0-9][A-Z][A-Z]'], ['NA'])
我希望通过使用[0-9] [AZ]的模式来处理一个数字和一个字母,然后[0-9] [AZ] [AZ]可以将任何单元格替换为2个字母,但文件保留完全一样,即使没有错误返回。
任何帮助将非常感激。
您可以使用pandas方法convert_objects
来执行此操作。您将设置convert_numeric
为True
convert_numeric:如果True强制转换为数字(包括字符串),则不可转换对象将获得NaN
>>> df
station_id year month element 1 2 3 4 5 6
0 216565 2008 7 SNOW 0TT 0 0 0 0 0
1 216565 2008 8 SNOW 0 0T 0 0 0 0
2 216565 2008 9 SNOW 0 0 0 0 0 0
>>> df.convert_objects(convert_numeric=True)
station_id year month element 1 2 3 4 5 6
0 216565 2008 7 SNOW NaN 0 0 0 0 0
1 216565 2008 8 SNOW 0 NaN 0 0 0 0
2 216565 2008 9 SNOW 0 0 0 0 0 0
如果您想使用的路线replace
,则需要修改通话。
>>> df
station_id year month element 1 2 3 4 5 6
0 216565 2008 7 SNOW 0TT 0 0 0 0 0
1 216565 2008 8 SNOW 0 0T 0 0 0 0
2 216565 2008 9 SNOW 0 0 0 0 0 0
>>> df1.replace(value=np.nan, regex=r'[0-9][A-Z]+')
station_id year month element 1 2 3 4 5 6
0 216565 2008 7 SNOW NaN 0 0 0 0 0
1 216565 2008 8 SNOW 0 NaN 0 0 0 0
2 216565 2008 9 SNOW 0 0 0 0 0 0
这还要求您导入numpy(import numpy as np
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句