Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于条件插入随机值_Python_Pandas_Numpy - Fatal编程技术网

Python 基于条件插入随机值

Python 基于条件插入随机值,python,pandas,numpy,Python,Pandas,Numpy,我有以下数据框,其中包含关于某个产品的各种信息。Input3是创建的句子列表,如下所示: sentence_list = (['Køb online her','Sammenlign priser her','Tjek priser fra 4 butikker','Se produkter fra 4 butikker', 'Stort udvalg fra 4 butikker','Sammenlign og køb']) df["Input3"] = np.random

我有以下数据框,其中包含关于某个产品的各种信息。Input3是创建的句子列表,如下所示:

sentence_list = (['Køb online her','Sammenlign priser her','Tjek priser fra 4 butikker','Se produkter fra 4 butikker', 'Stort udvalg fra 4 butikker','Sammenlign og køb'])
df["Input3"] = np.random.choice(sentence_list, size=len(df))
完整输入是通过连接各个列创建的字符串,其内容类似于:Brand-Buy online here-Sitename中的ProductName。它是这样创建的:

df["Full_Input"] = df['TitleTag'].astype(str) +  " " + df['Input2'].astype(str) + " " + df['Input3'].astype(str) + " " +  df['Input4'].astype(str) + " " +  df['Input5'].astype(str) 
这里的问题是,完整输入长度应小于55。因此,我试图找出如何在随机生成Input3时设置条件,这样当它与其他列的字符串相加时,完整的输入长度不会超过55

这就是我所尝试的:

for col in range(len(df)):
    condlist = [df["Full_Input"].apply(len) < 55]
    choicelist = [sentence_list]
    df['Input3_OK'][col] = np.random.choice.select(condlist, choicelist)
正如所料,它不是那样工作的。np.random.choice.select不是一件事,我得到了一个AttributeError


我该怎么做呢?

如果保证输入3中至少有一项满足此条件,您可能希望尝试类似于仅根据句子列表中的值调整随机选择,该值的长度可以接受:

转换为系列以启用熊猫过滤机制: 我的句子=[s代表句子列表中的s,如果镜头<最大长度] 从该筛选列表中随机选择: np.random.choicemy_句 换句话说,在调用random.choice之前,对每个字符串列表执行筛选

您可以对数据帧中的每一行运行此操作,如下所示:

def选择_stringfull_输入: 返回np.random.choice[ s 对于句子列表中的s 如果镜头+lenfull\u输入<55 ] df[Input3\u OK]=df.Full\u Input.mapchoose\u字符串