我写了一段代码,从时间戳列之一中提取月,时,周。我想在我的数据上的其他时间戳列上应用相同的代码,而无需重新编写代码。
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
<classpath>
<pathelement location="${env.ANT_HOME}/lib/ant-contrib-0.6.jar"/>
</classpath>
</taskdef>
答案 0 :(得分:3)
首先指定由日期时间填充的列,然后使用f-string
s循环创建新列:
cols = ['closed_at', 'another date col']
for x in cols:
incident_data[x] = pd.to_datetime(incident_data[x], errors='coerce')
incident_data[f'{x} - Month-Year'] = incident_data[x].dt.to_period('M')
incident_data[f'{x} - Weekday Num'] = incident_data[x].dt.dayofweek + 1
incident_data[f'{x} - Weekday'] = incident_data[x].dt.weekday_name
incident_data[f'{x} - Weekday Combo'] = (incident_data[f'{x} - Weekday Num'].astype(str)+
'-'+incident_data[f'{x} - Weekday'])
incident_data[f'{x} - Hour Num'] = incident_data[x].dt.hour
答案 1 :(得分:0)
您可以像这样在参数中声明具有列名和df的函数:
def transformation(df,column_name):
df[column_name] = pd.to_datetime(df[column_name], errors='coerce')
df['closed_at - Month-Year'] = df[column_name].dt.to_period('M')
df['closed_at - Weekday Num'] = df[column_name].dt.dayofweek + 1
df['closed_at - Weekday'] = df[column_name].dt.weekday_name
df['closed_at - Weekday Combo'] = df['closed_at - Weekday Num'].astype(str)+'-'+df['closed_at - Weekday']
df['closed_at - Hour Num'] = df[column_name].dt.hour
return df
然后,您可以使用名称列表在不同的列上进行迭代。
df = transformation(df,'closed_at')