鉴于:
从下面的df,
df = pd.DataFrame(
{"date":['2016-6-1', '2016-9-22', '2016-10-28', '2016-11-4', '2016-6-29', '2016-10-1', '2016-6-15', '2016-7-29', '2016-11-1'],
"score":[9, 8, 8, 10, 6, 7, 7, 7, 6]
})
执行以下任务:
对于满足以下条件的日期,向新添加的名为“staffNumber”的列添加特定值:
如果“日期”落在 6/1/2016~9/22/2016 之下,那么创建一个值为 1 的新列。
如果“日期”落在 9/23/2016~10/28/2016 下,则创建一个值为 2 的新列。
如果 'date' 落在 10/29/2016~11/4/2016 之下,那么创建一个值为 3 的新列
最终结果将如下所示:
df2 = pd.DataFrame(
{"date":['2016-6-1', '2016-9-22', '2016-10-28', '2016-11-4', '2016-6-29', '2016-10-1', '2016-6-15', '2016-7-29', '2016-11-1'],
"score":[9, 8, 8, 10, 6, 7, 7, 7, 6],
"staffNumber":[1,1,2,3,1,2,1,1,3]
})
我试过的:
在我提出任何问题之前,我通常会尝试一些东西。但是,对于这个,我想不出任何方法。
我从以下链接中查看了使用 np.where & .isin :
1. Python numpy where function with datetime
2. Using 'isin' on a date in a pandas column
3. Pandas conditional creation of a series/dataframe column
任何帮助将不胜感激!
最佳答案
使用 cut
:
#convert to datetimes if necessary
df['date'] = pd.to_datetime(df['date'])
b = pd.to_datetime(['2016-06-01','2016-09-22','2016-10-28','2016-11-04'])
l = range(1,4)
df['new'] = pd.cut(df['date'], bins=b, labels=l, include_lowest=True)
print (df)
date score new
0 2016-06-01 9 1
1 2016-09-22 8 1
2 2016-10-28 8 2
3 2016-11-04 10 3
4 2016-06-29 6 1
5 2016-10-01 7 2
6 2016-06-15 7 1
7 2016-07-29 7 1
8 2016-11-01 6 3
或
numpy.searchsorted
:#change first date to 2016-05-31
b = pd.to_datetime(['2016-05-31','2016-09-22','2016-10-28','2016-11-04'])
l = range(1,4)
df['new'] = np.array(l)[b.searchsorted(df['date'].values) - 1]
print (df)
date score new
0 2016-06-01 9 1
1 2016-09-22 8 1
2 2016-10-28 8 2
3 2016-11-04 10 3
4 2016-06-29 6 1
5 2016-10-01 7 2
6 2016-06-15 7 1
7 2016-07-29 7 1
8 2016-11-01 6 3
关于Python_Pandas : If datetime values fall under certain date duration, 创建具有特定值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47218138/