设置大于x到x的值,以及小于x到x的值

2024-04-26 19:11:32 发布

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

我试过了,但没能想出这个办法。我必须在下面的数据框中将所有大于3的数据更改为3,小于-3的数据更改为-3。你知道吗

np.random.seed(42)
randomdata = DataFrame(np.random.randn(400, 4))

我试过循环,.loc,.where,但似乎什么都没用。你知道吗


Tags: 数据dataframenprandomwhereloc中将seed
2条回答

编辑:对于熊猫来说,熊猫有DataFrame.clip。你知道吗

numpy.clip.

import numpy as np

thing = np.arange(-5, 6)  # [-5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5]

clipped_thing = np.clip(thing, -3, 3)

print(clipped_thing)

输出

[-3 -3 -3 -2 -1  0  1  2  3  3  3]
# Creating a data frame with 4 variables and 400 observations
np.random.seed(42)
randomdata = pd.DataFrame(np.random.randn(400, 4))
randomdata.head()

        0           1           2          3
0    0.496714   -0.138264    0.647689    1.523030
1   -0.234153   -0.234137    1.579213    0.767435
2   -0.469474    0.542560   -0.463418   -0.465730
3    0.241962   -1.913280   -1.724918   -0.562288
4   -1.012831    0.314247   -0.908024   -1.412304

# Cap and floor for one variable
randomdata[0].clip(lower=-0.5, upper=0.5)

# Cap and floor entire dataframe
clean_df = randomdata.clip(lower=-0.5, upper=0.5)
clean_df.head()

       0            1           2          3
0    0.496714   -0.138264    0.500000    0.50000
1   -0.234153   -0.234137    0.500000    0.50000
2   -0.469474    0.500000   -0.463418   -0.46573
3    0.241962   -0.500000   -0.500000   -0.50000
4   -0.500000    0.314247   -0.500000   -0.50000

相关问题 更多 >