Python 将字符串随机分配给列中的所有行
我有一个dataframePython 将字符串随机分配给列中的所有行,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['
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