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

Replace values of specific pattern with 'NaN' in csv file

我有一个与此类似的 csv 文件,但包含 1910-2010 年的大约 155,000 行和 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] 将用 2 替换任何单元格字母,但文件保持完全相同,即使没有返回错误。

如有任何帮助,我们将不胜感激。

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

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

returns:

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.genfromtxt 自动处理无效值。

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

您可以使用 pandas 方法 convert_objects 来完成此操作。您将 convert_numeric 设置为 True

convert_numeric : if True attempt to coerce to numbers (including strings), non-convertibles get 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)