用NaN替换数据框列中低于某个阈值的值

时间:2020-07-31 13:43:36

标签: python pandas dataframe nan nonetype

假设我有以下示例数据框:

alter session set constraints=deferred;

我试图用NaN替换某个阈值以下的列中的条目,使其看起来像这样:

Hibernate

这是我的尝试:

df = pd.DataFrame({'A': [4, 0.2, 3, 0.5], 'B': ['red', 'white', 'blue', 'green']})

     A      B
0  4.0    red
1  0.2  white
2  3.0   blue
3  0.5  green

还有我收到的错误:

     A      B
0  4.0    red
1  NaN  white
2  3.0   blue
3  NaN  green

我哪里出问题了?我认为这与cutoff = 2 df['A'] = df['A'].apply(lambda x: [y if y > cutoff else None for y in x]) 类型

有关

3 个答案:

答案 0 :(得分:1)

下面的代码对您有用吗?我用.loc[row_indexer,col_indexer] = value修改了数据框(link to the documentation

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [4, 0.2, 3, 0.5], 'B': ['red', 'white', 'blue', 'green']})
df.loc[df['A'] < 1, 'A'] = np.nan
print(df)

输出:

     A      B
0  4.0    red
1  NaN  white
2  3.0   blue
3  NaN  green

答案 1 :(得分:1)

请尝试:

df['A'] = df2['A'].apply(lambda x: x if x > cutoff else None)

答案 2 :(得分:1)

np.where

df['A'] = np.where(df['A']<=cutoff , np.nan, df['A'])