# 需求:想挑出小于特定值(比如40)的值,再将这些小于40的每个值随机赋值。
import pandas as pd
import random
old= [50,39,40,24,50,40,35,50,36,50]
other=[51,40,41,25,51,41,36,51,37,51]
df=pd.DataFrame({"old":old,"other":other})
# df=pd.read_csv("test.CSV")
print(df)
print("*"*50)
df["new1"]=df[df.old<40].apply(lambda x: random.randint(45,50),axis=1)
df["new2"]=df[df.old>=40].old
print(df)
print("+"*50)
df=df.fillna(0)
df["new"]=df["new1"]+df["new2"]
print(df)
print("-"*50)
df.to_csv("test条件筛选并随机填充.CSV")
"""
old other
0 50 51
1 39 40
2 40 41
3 24 25
4 50 51
5 40 41
6 35 36
7 50 51
8 36 37
9 50 51
**************************************************
old other new1 new2
0 50 51 NaN 50.0
1 39 40 50.0 NaN
2 40 41 NaN 40.0
3 24 25 49.0 NaN
4 50 51 NaN 50.0
5 40 41 NaN 40.0
6 35 36 47.0 NaN
7 50 51 NaN 50.0
8 36 37 48.0 NaN
9 50 51 NaN 50.0
++++++++++++++++++++++++++++++++++++++++++++++++++
old other new1 new2 new
0 50 51 0.0 50.0 50.0
1 39 40 50.0 0.0 50.0
2 40 41 0.0 40.0 40.0
3 24 25 49.0 0.0 49.0
4 50 51 0.0 50.0 50.0
5 40 41 0.0 40.0 40.0
6 35 36 47.0 0.0 47.0
7 50 51 0.0 50.0 50.0
8 36 37 48.0 0.0 48.0
9 50 51 0.0 50.0 50.0
--------------------------------------------------
--------------------------------------------------
"""