Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.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_Python 3.x_Pandas_Dataframe - Fatal编程技术网

Python 将字符串随机分配给列中的所有行

Python 将字符串随机分配给列中的所有行,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我有一个dataframedf['type'],其中我想随机分配两个字符串值中的一个:hello,bye to all rows in this column。如何执行此操作?与数据帧的长度一起使用: df['type'] = np.random.choice(['hello','bye'], size=len(df)) 对于布尔值: df['type'] = np.random.choice([True, False], size=len(df)) 或: 与数据帧的长度一起使用: df['

我有一个dataframe
df['type']
,其中我想随机分配两个字符串值中的一个:hello,bye to all rows in this column。如何执行此操作?

数据帧的长度一起使用:

df['type'] = np.random.choice(['hello','bye'], size=len(df))
对于布尔值:

df['type'] = np.random.choice([True, False], size=len(df))
或:

与数据帧的长度一起使用:

df['type'] = np.random.choice(['hello','bye'], size=len(df))
对于布尔值:

df['type'] = np.random.choice([True, False], size=len(df))
或:

随机使用模块

random.choice(["hello","bye"])
随机使用模块

random.choice(["hello","bye"])

np.random.choice
np.random.choice
?这可以修改为分配布尔值(0/1)吗?@x89-当然,将
['hello','bye']
更改为
[0,1]
,对于布尔
np.random.choice([0,1],size=len(df),dtype=bool)
random.choice()
在标准库中。无需使用numpy。@Bachsau For performance使用np.random.choice也可以修改为分配布尔值(0/1)?@x89-当然,将
['hello','bye']
更改为
[0,1]
,用于布尔
np.random。choice([0,1],size=len(df),dtype=bool)
random.choice()
在标准库中。不需要使用numpy。@Bachsau For performance用于np.random.choice