楼主: yunnandlg
1044 1

条件筛选并随机填充 [推广有奖]

版主

但问耕耘,莫问收获

已卖:3032份资源

院士

5%

还不是VIP/贵宾

-

威望
0
论坛币
279697 个
通用积分
649.6470
学术水平
1667 点
热心指数
1686 点
信用等级
1650 点
经验
192222 点
帖子
1938
精华
0
在线时间
2781 小时
注册时间
2010-8-28
最后登录
2026-1-1

楼主
yunnandlg 在职认证  学生认证  发表于 2020-3-21 15:29:22 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币

# 需求:想挑出小于特定值(比如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
--------------------------------------------------
--------------------------------------------------
"""


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:条件筛选 Dataframe import pandas random

Cause morning rolls around and it's another day of sun.
清晨不久就会来到,又是阳光明媚的一天。

沙发
yunnandlg 在职认证  学生认证  发表于 2020-3-22 08:28:19
The future has not been written. There is no fate but what we make for ourselves.

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2026-1-2 09:59