gpt4 book ai didi

python - 如何跨多列循环类似的python pandas代码

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:36 26 4
gpt4 key购买 nike

我编写了一段代码,用于从其中一个时间戳列中提取月、小时、工作日。我想在我的数据的其他时间戳列中应用相同的代码,而无需重写代码。

df['closed_at'] = pd.to_datetime(df['closed_at'], errors='coerce')
df['closed_at - Month-Year'] = df['closed_at'].dt.to_period('M')
df['closed_at - Weekday Num'] = df['closed_at'].dt.dayofweek + 1
df['closed_at - Weekday'] = df['closed_at'].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['closed_at'].dt.hour

最佳答案

首先指定由日期时间填充的列,然后使用 f-strings 在循环中创建新列:

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

关于python - 如何跨多列循环类似的python pandas代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56598493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com