我有两个现有列的数据框pyspark DFname
并birthdate
为此我要使用随机值覆盖值。
对于列,name
我想要一个字符串,其中包含一组固定长度的随机字母(比如 10)。字符串应该为每一行随机化,这样所有行都不会得到相同的字符串。
对于列,birthdate
我想要一个字符串格式YYYY-MM-DD
。我希望每一行在1960-01-01
和之间都有一个随机值2019-01-01
。
我怎样才能做到这一点?
您可以创建随机字符串
''.join(random.choice(string.ascii_lowercase) for x in range(size))
和随机日期
month = random.randint(1, 12)
str(random.randint(1960, 2018)) + '-' + str(month)+'-' + (str(random.randint(1, 28)) if month == 2 else str(random.randint(1, 30)) if month % 2 == 0 else str(random.randint(1, 31)))
不要忘记import random
和import string
。
要创建具有数据框形状的数组,请创建具有相同大小的 numpy.ndarray
import numpy as np
arr = np.ndarray(2, len(dataframe[0]))
然后通过循环给它正确的值
for y in range(len(dataframe[0])):
arr[0, y] = ''.join(random.choice(string.ascii_lowercase) for x in range(size))
month = random.randint(1, 12)
arr[1, y] =str(random.randint(1960, 2018)) + '-' + str(month)+'-' + (str(random.randint(1, 28)) if month == 2 else str(random.randint(1, 30)) if month % 2 == 0 else str(random.randint(1, 31)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句