替换pandas数据帧中大于数字的值

Zan*_*nam 15 python database pandas

我有一个大型数据框,看起来像:

df1['A'].ix[1:3]
2017-01-01 02:00:00    [33, 34, 39]
2017-01-01 03:00:00    [3, 43, 9]
Run Code Online (Sandbox Code Playgroud)

我想用11替换大于9的每个元素.

因此,上述示例的所需输出为:

df1['A'].ix[1:3]
2017-01-01 02:00:00    [11, 11, 11]
2017-01-01 03:00:00    [3, 11, 9]
Run Code Online (Sandbox Code Playgroud)

编辑:

我的实际数据帧大约有20,000行,每行有2000个大小的列表.

有没有办法numpy.minimum为每一行使用函数?我认为它会比list comprehension方法更快?

D.G*_*ths 18

您可以使用 numpy 索引,通过.values函数访问。

df['col'].values[df['col'].values > x] = y

用 y 的值替换任何大于 x 的值。

因此,对于问题中的示例:

df1['A'].values[df1['A'] > 9] = 11

  • 这是我能找到的最好的解决方案,并且按预期工作。 (2认同)

jez*_*ael 13

你可以用applylist comprehension:

df1['A'] = df1['A'].apply(lambda x: [y if y <= 9 else 11 for y in x])
print (df1)
                                A
2017-01-01 02:00:00  [11, 11, 11]
2017-01-01 03:00:00    [3, 11, 9]
Run Code Online (Sandbox Code Playgroud)

更快的解决方案首先转换为numpy array然后使用numpy.where:

a = np.array(df1['A'].values.tolist())
print (a)
[[33 34 39]
 [ 3 43  9]]

df1['A'] = np.where(a > 9, 11, a).tolist()
print (df1)
                                A
2017-01-01 02:00:00  [11, 11, 11]
2017-01-01 03:00:00    [3, 11, 9]
Run Code Online (Sandbox Code Playgroud)


小智 11

我知道这是一个旧帖子,但熊猫现在DataFrame.where直接支持。在你的例子中:

df.where(df <= 9, 11, inplace=True)
Run Code Online (Sandbox Code Playgroud)

请注意,pandaswherenumpy.where. 在 Pandas 中,当 时condition == True,使用数据帧中的当前值。当 时condition == False,取另一个值。

编辑:

您只需使用以Series.where下列即可实现相同的效果:

df['A'].where(df['A'] <= 9, 11, inplace=True)
Run Code Online (Sandbox Code Playgroud)


Edo*_*uny 10

非常简单: df[df > 9] = 11

  • 解决方案是错误的,因为不使用输入数据. (4认同)

CFW*_*CFW 6

我来找一个解决方案,将每个大于 h 的元素替换为 1 否则 0,它有一个简单的解决方案:

df = (df > h) * 1
Run Code Online (Sandbox Code Playgroud)

(这并不能解决OP的问题,因为所有 df <= h 都被 0 替换。)

  • 因为标题(导致我和可能的其他人来到这里)不精确,可能暗示这个答案。 (7认同)
  • 如果它没有回答OP的问题,为什么要把它写成答案? (2认同)