如何替换条件上数据帧的值



我有一个超过50列的熊猫数据帧。除第一列外的所有数据都是浮点数。我想用 100 替换任何大于 5.75 的值。有人可以建议任何功能也这样做吗?

替换函数不起作用,因为to_value只能采用"="函数,而不能采用大于函数。

这可以使用

df['ColumnName'] = np.where(df['ColumnName'] > 5.75, 100, df['First Season'])

您可以创建一个自定义函数并将其传递给应用程序:

import pandas as pd
import random
df = pd.DataFrame({'col_name': [random.randint(0,10) for x in range(100)]})
def f(x):
if x >= 5.75:
return 100
return x
df['modified'] = df['col_name'].apply(f)
print(df.head())
col_name  modified
0         2         2
1         5         5
2         7       100
3         1         1
4         9       100

如果您有数据帧:

import pandas as pd
import random
df = pd.DataFrame({'first_column': [random.uniform(5,6) for x in range(10)]})
print(df)

给我:

first_column
0  5.620439
1  5.640604
2  5.286608
3  5.642898
4  5.742910
5  5.096862
6  5.360492
7  5.923234
8  5.489964
9  5.127154

然后检查该值是否大于 5.75:

df[df > 5.75] = 100
print(df)

给我:

first_column
0    5.620439
1    5.640604
2    5.286608
3    5.642898
4    5.742910
5    5.096862
6    5.360492
7  100.000000
8    5.489964
9    5.127154
import numpy as np
import pandas as pd
#Create df
np.random.seed(0)
df = pd.DataFrame(2*np.random.randn(100,50))
for col_name in df.columns[1:]: #Skip first column
df.loc[:,col_name][df.loc[:,col_name] > 5.75] = 100
np.where(df.value > 5.75, 100, df.value)

最新更新