带有Datetime列的pandas条件str concat(多项选择)

时间:2019-05-17 13:09:14

标签: string pandas datetime conditional concat

这是一个后续问题:以前,Ive仅将“日期”列中的年份与前一天结合使用,以使其看起来像“ day-ahead_2019”或“ day-ahead_2018”,具体取决于“日期”列中的年份

我有两列:

DELIVERY_PERIOD   
day-ahead
day-ahead
week-ahead
month-ahead
week1_2019
week2_2018

Date
13/05/2019
14/05/2019
11/05/2019
10/05/2019

现在,我有多个条目要设为“ xxxxx_year” 因此,我尝试为想要的人创建一个过滤器列表,并使用相同的代码得到此“ TypeError:'int'对象不可迭代” 不知道这是我生成过滤器列表的方式

所以这是为我想要的单个str工作的代码

    gas.loc[gas['Period'] == 'Day-ahead','Period'] = gas['Period'] + '_' + gas['Date'].dt.year.astype(str)

如果我生成过滤器列表

    filterlist = gas[gas['Period'].isin(['week-ahead','month-ahead',"day-ahead"])]

    gas.loc[gas['Period'] == filterlist,'Period'] = gas['Period'] + '_' + gas['Date'].dt.year.astype(str)

给我TypeError:“ int”对象不可迭代

2 个答案:

答案 0 :(得分:2)

为我曾经使用过的任何人找出解决方法:

    gas.loc[gas['Period'].isin(['week-ahead','month-ahead',"day-ahead"]),'Period'] = gas['Period'] + '_' + gas['Date'].dt.year.astype(str)

答案 1 :(得分:0)

尝试在此处使用numpy。

gas['Period]= np.where((gas['Period'].isin(['week-ahead','month-ahead','day-ahead']), gas['Period'] + '_' + gas['Date'].dt.year.astype(str), gas['Period'])

在这种情况下,您仅覆盖应用过滤器的列,旧的保持不变

否则,首先过滤您的数据框,然后更改列: gas = gas[gas['Period'].isin(['week-ahead','month-ahead',"day-ahead"])]

gas['Period'] = gas['Period'] + '_' + gas['Date'].dt.year.astype(str)