如何用pandas中的值替换字符串?

时间:2019-01-20 09:35:39

标签: python-3.x pandas

使用read_csv()从csv文件中获取数据。现在它们是熊猫数据框。它们可能如下所示。

1     2 11    
inf   2  1
1   inf  3

我使用了代码:

df = df.replace('inf', 1000000)

df.replace('inf', 1000000, inplace=True)

因此它们不能将inf字符串替换为标量1000000。

如何用1000000替换inf?

2 个答案:

答案 0 :(得分:2)

使用np.inf,因为'inf'inf的字符串表示形式:

print (df)
          a         b   c
0  1.000000  2.000000  11
1       inf  2.000000   1
2  1.000000       inf   3

df = df.replace(np.inf, 1000000)

print (df)
           a          b   c
0        1.0        2.0  11
1  1000000.0        2.0   1
2        1.0  1000000.0   3

答案 1 :(得分:1)

如果建立上限,我建议使用df.clip_upper

df.clip_upper(1000000)

           a          b     c
0        1.0        2.0  11.0
1  1000000.0        2.0   1.0
2        1.0  1000000.0   3.0

否则,您可以使用np.isfinite并设置值:

df.where(np.isfinite(df), 1000000)
# df.mask(~np.isfinite(df), 1000000)

           a          b   c
0        1.0        2.0  11
1  1000000.0        2.0   1
2        1.0  1000000.0   3

如果不影响NaN,请使用

df.where(np.isfinite(df) | np.isnan(df), 1000000)

           a          b   c
0        1.0        2.0  11
1  1000000.0        2.0   1
2        1.0  1000000.0   3

您也可以使用isin进行此操作:

df.where(~df.isin([np.inf]), 1000000)
# df.where(~np.isin(df, np.inf), 1000000)
# df.mask(df.isin([np.inf]), 1000000)

           a          b   c
0        1.0        2.0  11
1  1000000.0        2.0   1
2        1.0  1000000.0   3

使用np.where有上述版本的现成版本:

df[:] = np.where(np.isin(df, np.inf), 10000000, df)

或者,

pd.DataFrame(np.where(np.isin(df, np.inf), 10000000, df), 
             index=df.index, 
             columns=df.columns)

           a          b   c
0        1.0        2.0  11
1  1000000.0        2.0   1
2        1.0  1000000.0   3

性能

df_ = df.copy()
df = pd.concat([df_] * 10000, ignore_index=True)

%timeit df.replace(np.inf, 1000000)
%timeit df.where(np.isfinite(df) | np.isnan(df), 1000000)
%timeit df.where(np.isfinite(df), 1000000)
%timeit df.clip_upper(1000000)

9.44 ms ± 157 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
4.26 ms ± 38.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
3.37 ms ± 114 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
605 µs ± 17.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)