且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-26 17:25:49

您可以将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]

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

Faster solution is first convert to numpy array and then use 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]