按日期从数据框的列中随机选择行

时间:2020-04-27 19:46:18

标签: python pandas dataframe

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

我在没有每日说明的情况下问了同样的问题:Randomly selecting rows from dataframe column

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

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 

1 个答案:

答案 0 :(得分:2)

您可以使用groupbysample,获取index值,然后使用loc创建列x4,并使用-1乘以列创建fillna,例如:< / p>

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'])