【问题标题】:How to create new column with conditional datetime using pandas如何使用熊猫创建具有条件日期时间的新列
【发布时间】:2019-01-29 06:07:53
【问题描述】:

我正在尝试添加一个包含具有这种条件的标签的新列:

  • 标签 1 如果 'time' 中的值与 dt 之间的时间差
  • 标签 0 表示其他情况

我目前的想法:

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)

但我得到了错误:'Series 的真值是模棱两可的。使用 a.empty, a.bool()...

有没有办法解决这个问题?

【问题讨论】:

  • 我认为您的意思是在label 的函数定义中使用c,而不是在全局范围内使用整个df

标签: python pandas datetime dataframe


【解决方案1】:

如果想设置字符串01

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

如果要设置整数01

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'

【讨论】:

  • 我很接近np.where(dt-df['time']&lt;a).astype(int).astype(str) :)
猜你喜欢
  • 2021-02-12
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-15
  • 2017-09-24
  • 2020-05-15
相关资源
最近更新 更多