【发布时间】:2020-11-18 11:59:42
【问题描述】:
我正在尝试返回数据框中类型为 datetime 的字段,然后将字段名称替换为“date”,以便将 datetime 拆分为年份和月份。
当我运行代码时它崩溃并显示以下错误:
df = df.rename(columns={converteddate[0]: 'date'})
UnboundLocalError: local variable 'converteddate' referenced before assignment
代码:
import pandas as pd
df = pd.DataFrame({'event_type': ['watch movie ', 'stay at home', 'swimming','camping','meeting'],
'date': ['8/11/2020', '2/13/2020', '7/04/2020','1/22/2020','7/28/2020'],
'event_mohafaza':['loc1','loc3','loc2','loc5','loc4'],
' number_person ':[24,39,20,10,33],})
non_numeric_cols = [col for col, col_type in df.dtypes.iteritems() if col_type == 'object']
if len(non_numeric_cols) > 0:
mask = df.astype(str).apply(lambda x : x.str.match('[0-3]?[0-9]-[0-3]?[0-9]-(?:[0-9]{2})?[0-9]{2}$').any())
if mask.any() == True:
df.loc[:,mask] = df.loc[:,mask].apply(pd.to_datetime,dayfirst=False)
converteddate = [col for col in df.columns if df[col].dtype == 'datetime64[ns]']
df = df.rename(columns={converteddate[0]: 'date'})
if "date" in df.columns:
df['year_month'] = df['date'].map(lambda x: x.strftime('%Y/%m'))
【问题讨论】:
标签: python dataframe datetime strftime