Python 测试列是否为日期时间类型
我试图用一个合适的变量对每列Python 测试列是否为日期时间类型,python,pandas,numpy,Python,Pandas,Numpy,我试图用一个合适的变量对每列填充。我的目标是尝试在通用性的最高级别上找到列类型:基本上,目前它要么是数字(int/float)、字符串,要么是pandasTimestamp。我知道我可以使用numpy.issubdtype和检测数字或字符串,但我还没有找到检测时间戳的方法。我的解决方案使用了iloc[0]和isinstance,但还有更好的吗?这是我的代码,大致如下: for col in df: if np.issubdtype(dataframe[col].dtype, np.num
填充。我的目标是尝试在通用性的最高级别上找到列类型:基本上,目前它要么是数字(int/float)、字符串,要么是pandasTimestamp
。我知道我可以使用numpy.issubdtype
和检测数字或字符串,但我还没有找到检测时间戳的方法。我的解决方案使用了iloc[0]
和isinstance
,但还有更好的吗?这是我的代码,大致如下:
for col in df:
if np.issubdtype(dataframe[col].dtype, np.number):
df[col] = df[col].fillna(-1)
elif isinstance(dataframe[col].iloc[0], pd.datetime):
df[col] = df[col].fillna(pd.to_datetime('1900-01-01'))
else:
df[col] = df[col].fillna('NaN')
return (dataframe.fillna(na_var)
(注意,我不能使用df.loc[0,col]
,因为我的索引并不总是包含0。)从我这里开始,np.issubdtype(df[col].dtype,np.datetime64)
做你想做的事
综上所述,我们有:
def df_fillna(df):
for col in df:
if np.issubdtype(df[col].dtype, np.number):
df[col] = df[col].fillna(-1)
elif np.issubdtype(df[col].dtype, np.datetime64):
df[col] = df[col].fillna(pd.to_datetime('1900-01-01'))
else:
df[col] = df[col].fillna('NaN')
return df
举个例子。输入:
df_test = pd.DataFrame()
df_test['dates'] = [pd.to_datetime("2009-7-23"), pd.to_datetime("2011-7-7"), pd.NaT]
df_test = df_fillna(df_test)
输出:
dates
0 2009-07-23
1 2011-07-07
2 1900-01-01
对我来说,np.issubdtype(df[col].dtype,np.datetime64)
做你想做的事
综上所述,我们有:
def df_fillna(df):
for col in df:
if np.issubdtype(df[col].dtype, np.number):
df[col] = df[col].fillna(-1)
elif np.issubdtype(df[col].dtype, np.datetime64):
df[col] = df[col].fillna(pd.to_datetime('1900-01-01'))
else:
df[col] = df[col].fillna('NaN')
return df
举个例子。输入:
df_test = pd.DataFrame()
df_test['dates'] = [pd.to_datetime("2009-7-23"), pd.to_datetime("2011-7-7"), pd.NaT]
df_test = df_fillna(df_test)
输出:
dates
0 2009-07-23
1 2011-07-07
2 1900-01-01
啊,这么简单,真不敢相信我错过了。谢谢啊,这么简单,真不敢相信我错过了。谢谢