Pandas:如何有条件地分配多个列?

2024-05-01 21:37:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想用nan替换某些列的负值。最简单的方法是:

for col in ['a', 'b', 'c']:
    df.loc[df[col ] < 0, col] = np.nan

df可以有许多列,我只想对特定列执行此操作。在

有没有一种方法可以做到这一点?看起来这应该很容易,但我一直没能弄明白。在


Tags: 方法indffornpcolnanloc
3条回答

有个办法:

df[df.columns.isin(['a', 'b', 'c']) & (df < 0)] = np.nan

使用loc和{}

cols = ['a', 'b', 'c']
df.loc[:, cols] = df[cols].where(df[cols].where.ge(0), np.nan)

演示

^{pr2}$

enter image description here

cols = list('abc')
df.loc[:, cols] = df[cols].where(df[cols].ge(0), np.nan)
df

enter image description here


你可以用numpy加速

df[cols] = np.where(df[cols] < 0, np.nan, df[cols])

做同样的事情。在


定时

def gen_df(n):
    return pd.DataFrame(np.random.randn(n, 5), columns=list('abcde'))

由于赋值是其中的一个重要部分,所以我从头开始创建df每个循环。我还添加了创建df的计时。在

对于n = 10000

enter image description here

对于n = 100000

enter image description here

我不认为你会比这简单得多:

>>> df = pd.DataFrame({'a': np.arange(-5, 2), 'b': np.arange(-5, 2), 'c': np.arange(-5, 2), 'd': np.arange(-5, 2), 'e': np.arange(-5, 2)})
>>> df
   a  b  c  d  e
0 -5 -5 -5 -5 -5
1 -4 -4 -4 -4 -4
2 -3 -3 -3 -3 -3
3 -2 -2 -2 -2 -2
4 -1 -1 -1 -1 -1
5  0  0  0  0  0
6  1  1  1  1  1
>>> df[df[cols] < 0] = np.nan
>>> df
     a    b    c  d  e
0  NaN  NaN  NaN -5 -5
1  NaN  NaN  NaN -4 -4
2  NaN  NaN  NaN -3 -3
3  NaN  NaN  NaN -2 -2
4  NaN  NaN  NaN -1 -1
5  0.0  0.0  0.0  0  0
6  1.0  1.0  1.0  1  1

相关问题 更多 >