将特定模式的值替换为 csv 文件中的'NaN'



我有一个类似的csv文件,但大约有155000行,年份为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][A-Z]的模式来处理一个数字和一个字母,然后[0-9][A-Z][A-Z]将用两个字母替换任何单元格,但即使没有返回错误,文件也保持完全相同。

任何帮助都将不胜感激。

您可以使用panda方法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

str.replace不执行正则表达式。使用re模块(假设df是字符串):

import re
re.sub(r'[0-9][A-Z]+', 'NaN', df)

退货:

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

但是,最好让Pandas或np.genfromttxt自动处理无效值。

from re import sub
string = "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"
string = sub(r'd{1}[A-Za-z]{1,2}', 'NaN', string)
print string
# 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

最新更新