按日期从数据框的列中随机选择行 [英] Randomly selecting rows from dataframe column by date

查看:61
本文介绍了按日期从数据框的列中随机选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于给定的dataframe列,我想随机选择按天,并添加到新列中,将剩余的40%添加到另一列中,再将40%列乘以( -1),并创建一个新列,将每一天合并在一起(这样我每天的比率为60/40)

For a given dataframe column, I would like to randomly select by day roughly 60% and add to a new column, add the remaining 40% to another column, multiply the 40% column by (-1), and create a new column that merges these back together for each day (so that each day I have a ratio of 60/40):

我在这里没有每日规范地问了同样的问题:从数据框列中随机选择行

I have asked the same question without the daily specification here: Randomly selecting rows from dataframe column

下面的示例说明了这一点(尽管我的比率并不完全是60/40):

Example below illustrates this (although my ratio is not exactly 60/40 there):

dict0 = {'date':[1/1/2019,1/1/2019,1/1/2019,1/2/2019,1/1/2019,1/2/2019],'x1': [1,2,3,4,5,6]}
df = pd.DataFrame(dict0)### 
df['date']      = pd.to_datetime(df['date']).dt.date 

dict1 = {'date':[1/1/2019,1/1/2019,1/1/2019,1/2/2019,1/1/2019,1/2/2019],'x1': [1,2,3,4,5,6],'x2': [1,'nan',3,'nan',5,6],'x3': ['nan',2,'nan',4,'nan','nan']}
df = pd.DataFrame(dict1)### 
df['date']      = pd.to_datetime(df['date']).dt.date 

dict2 = {'date':[1/1/2019,1/1/2019,1/1/2019,1/2/2019,1/1/2019,1/2/2019],'x1': [1,2,3,4,5,6],'x2': [1,'nan',3,'nan',5,6],'x3': ['nan',-2,'nan',-4,'nan','nan']}
df = pd.DataFrame(dict2)### 
df['date']      = pd.to_datetime(df['date']).dt.date 

dict3 = {'date':[1/1/2019,1/1/2019,1/1/2019,1/2/2019,1/1/2019,1/2/2019],'x1': [1,2,3,4,5,6],'x2': [1,'nan',3,'nan',5,6],'x3': ['nan',-2,'nan',-   4,'nan','nan'],'x4': [1,-2,3,-4,5,6]}
df = pd.DataFrame(dict3)### 
df['date']      = pd.to_datetime(df['date']).dt.date 


推荐答案

您可以使用 groupby sample ,获取 index 值,然后用loc创建列x4,并用-1乘以 fillna 像这样的列:

you can use groupby and sample, get the index values, then create the column x4 with loc, and fillna with the -1 multiplied column like:

idx= df.groupby('date').apply(lambda x: x.sample(frac=0.6)).index.get_level_values(1)
df.loc[idx, 'x4'] = df.loc[idx, 'x1']
df['x4'] = df['x4'].fillna(-df['x1'])

这篇关于按日期从数据框的列中随机选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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