我正在尝试添加一个包含带有以下条件的标签的新列:
我当前的想法:
df = pd.read_csv('./datetimecek.csv')
df['time'] = pd.to_datetime(df['datetime'])
dt = datetime.strptime("19/02/18 19:00", "%d/%m/%y %H:%M")
datetime time
2018/02/19 16:00 2018-02-19 16:00:00
2018/02/19 17:00 2018-02-19 17:00:00
2018/02/19 18:00 2018-02-19 18:00:00
2018/02/19 19:00 2018-02-19 19:00:00
然后我定义了timedelta
a = timedelta(hours=2)
def label(c):
if dt - df['time'] < a:
return '1'
else:
return '0'
然后
df['label'] = df.apply(label, axis=1)
但是我得到了一个错误:“系列的真实价值是模棱两可的。使用a.empty,a.bool()...
反正我可以解决这个问题吗?
答案 0 :(得分:1)
如果要设置字符串0
和1
:
df['label'] = np.where(dt - df['time'] < a, '1','0')
或由@Dark替代:
df['label'] = (dt - df['time'] < a).astype(int).astype(str)
print (df)
datetime time label
0 2018/02/19 16:00 2018-02-19 16:00:00 0
1 2018/02/19 17:00 2018-02-19 17:00:00 0
2 2018/02/19 18:00 2018-02-19 18:00:00 1
3 2018/02/19 19:00 2018-02-19 19:00:00 1
print (type(df.loc[0, 'label']))
<class 'str'>
如果要设置整数0
和1
:
df['label'] = (dt - df['time'] < a).astype(int)
替代:
df['label'] = np.where(dt - df['time'] < a, 1,0)
print (df)
datetime time label
0 2018/02/19 16:00 2018-02-19 16:00:00 0
1 2018/02/19 17:00 2018-02-19 17:00:00 0
2 2018/02/19 18:00 2018-02-19 18:00:00 1
3 2018/02/19 19:00 2018-02-19 19:00:00 1
print (type(df.loc[0, 'label']))
<class 'numpy.int32'>
反正我可以解决这个问题吗?
是的,需要将df
更改为c
才能使用标量:
def label(c):
if dt - c['time'] < a:
return '1'
else:
return '0'