我的df
包含n
columns
。其中一个是名为column
的{{1}},其中包含格式为date
的值。现在我想向mm-dd-yy
添加column
interval
。此df
应该返回column
中包含的year
,但如果它是date
或H1
。 H2
为半年,H1
date
之间的01-dd-yy
值应为06-dd-yy
,因此H2
应为date
之间的所有07-dd-yy
值}和12-dd-yy
。
这是df['date']
:
0 01-27-16
1 02-27-16
2 03-27-16
3 04-27-16
4 05-27-16
5 06-27-16
6 07-27-16
7 08-24-16
8 09-24-16
9 10-16-15
...etc...
在df
我想添加另一个名为interval
的列,其中包含:
0 16H1
1 16H1
2 16H1
3 16H1
4 16H1
5 16H1
6 16H2
7 16H2
8 16H2
9 15H2
...etc...
所以我想我会创建一个function
,然后使用map
。
def is_in_range(x):
if x['date'] >= '01-01-16' x['date'] <= '06-31-16':
print '16H1'
elif x['date'] >= '07-01-16' and x['date'] <= '12-31-16':
print '16H2'
elif x['date'] >= '01-01-15' and x['date'] <= '06-31-15':
print '15H1'
elif x['date'] >= '07-01-15' and x['date'] <= '12-31-15':
print '15H2'
...etc...
我这样称呼函数:
df.groupby(df['date'].map(is_in_range))
现在这给了我:
`TypeError:'Timestamp'对象没有属性' getitem '
开头。我不知道为什么,但无论哪种方式肯定都有更好的方法?
答案 0 :(得分:1)
您可以使用dt.quarter
或dt.month
。
首先按astype
将int
年份值转换为str
,然后选择最后2
个字符。最后一次使用numpy.where
条件:
#first convert to datetime if not datetime
df.date = pd.to_datetime(df.date)
df['interval'] = df.date.astype(str).str[2:4] + np.where(df.date.dt.month < 7, 'H1','H2')
print (df)
date interval
0 2016-01-27 16H1
1 2016-02-27 16H1
2 2016-03-27 16H1
3 2016-04-27 16H1
4 2016-05-27 16H1
5 2016-06-27 16H1
6 2016-07-27 16H2
7 2016-08-24 16H2
8 2016-09-24 16H2
9 2015-10-16 15H2
或者:
df['interval'] = df.date.astype(str).str[2:4] + np.where(df.date.dt.quarter < 3,'H1','H2')
print (df)
date interval
0 2016-01-27 16H1
1 2016-02-27 16H1
2 2016-03-27 16H1
3 2016-04-27 16H1
4 2016-05-27 16H1
5 2016-06-27 16H1
6 2016-07-27 16H2
7 2016-08-24 16H2
8 2016-09-24 16H2
9 2015-10-16 15H2
string
解决方案:
df['interval'] = df.date.str[6:] + np.where(df.date.str[:2].astype(int) < 7, 'H1','H2')
print (df)
date interval
0 01-27-16 16H1
1 02-27-16 16H1
2 03-27-16 16H1
3 04-27-16 16H1
4 05-27-16 16H1
5 06-27-16 16H1
6 07-27-16 16H2
7 08-24-16 16H2
8 09-24-16 16H2
9 10-16-15 15H2
列表理解解决方案即使不是 NaN :
也能正常工作 string
专栏:
df['interval'] = [x[6:] + 'H1' if int(x[:2])< 7 else x[6:] + 'H2' for x in df['date']]
datetime
专栏:
#first convert to datetime if not datetime
df.date = pd.to_datetime(df.date)
df['interval'] = [x[2:4] + 'H1' if int(x[5:7])< 7 else x[2:4] + 'H2' for x in df['date'].astype(str)]
print (df)
date interval
0 01-27-16 16H1
1 02-27-16 16H1
2 03-27-16 16H1
3 04-27-16 16H1
4 05-27-16 16H1
5 06-27-16 16H1
6 07-27-16 16H2
7 08-24-16 16H2
8 09-24-16 16H2
9 10-16-15 15H2
答案 1 :(得分:1)
是'日期'列的字符串吗?你不能真正比较那样的字符串
将字符串中的最后两个元素转换为int
A = [x[6:]+'H1' if int(x[6:]+)< 7 else 'H2' for x in df['date'].values]
最后
df['interval'] = A