如何将列表中的随机值分配给pandas数据框中的列? [英] How to assign random values from a list to a column in a pandas dataframe?

查看:114
本文介绍了如何将列表中的随机值分配给pandas数据框中的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Bigquery中使用Python,并且具有较大的数据框df(大约7m行).我还有一个列表lst,其中包含一些日期(例如,给定月份中的所有天).

I am working with Python in Bigquery and have a large dataframe df (circa 7m rows). I also have a list lst that holds some dates (say all days in a given month).

我正在尝试在df中创建一个附加列"random_day",并在每行中使用lst中的随机值.

I am trying to create an additional column "random_day" in df with a random value from lst in each row.

我尝试运行循环并应用函数,但由于数据集很大,因此极富挑战性.

I tried running a loop and apply function but being quite a large dataset it is proving challenging.

我的尝试通过了循环解决方案:

My attempts passed by the loop solution:

df["rand_day"] = ""

for i in a["row_nr"]:
  rand_day = sample(day_list,1)[0]
  df.loc[i,"rand_day"] = rand_day

然后是应用解决方案,首先定义我的函数,然后调用它:

And the apply solution, defining first my function and then calling it:

def random_day():
  rand_day = sample(day_list,1)[0]
  return day

df["rand_day"] = df.apply(lambda row: random_day())

对此有任何提示吗? 谢谢

Any tips on this? Thank you

推荐答案

使用 numpy.random.choice ,并在必要时通过 to_datetime :

df = pd.DataFrame({
        'A':list('abcdef'),
        'B':[4,5,4,5,5,4],
})

day_list = pd.to_datetime(['2015-01-02','2016-05-05','2015-08-09'])
#alternative
#day_list = pd.DatetimeIndex(['2015-01-02','2016-05-05','2015-08-09'])

df["rand_day"] = np.random.choice(day_list, size=len(df))
print (df)
   A  B   rand_day
0  a  4 2016-05-05
1  b  5 2016-05-05
2  c  4 2015-08-09
3  d  5 2015-01-02
4  e  5 2015-08-09
5  f  4 2015-08-09

这篇关于如何将列表中的随机值分配给pandas数据框中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆