繁体   English   中英

如何在Pandas DataFrame中检查列值的类型

[英]How to check a type of column values in pandas DataFrame

我可以使用df.dtypes检查列类型,其中df是pandas DataFrame。 但是,我的问题有点不同。 我有以下DataFrame:

col1 col2
0    <class 'pandas._libs.tslibs.timestamps.Timestamp'>
1    <class 'pandas._libs.tslibs.timestamps.Timestamp'>
2    <class 'float'>
3    NaN
4    <class 'pandas._libs.tslibs.timestamps.Timestamp'>

df["col2"].dtypes返回object

我需要创建一个新列is_timestamp ,它将检查col2值是否为pandas时间戳。 为了进行测试,我尝试了以下代码:

isinstance(df_viz["col2"][0], pd._libs.tslibs.timestamps.Timestamp)

但是它返回False

预期输出:

col1 col2                                                 col3
0    <class 'pandas._libs.tslibs.timestamps.Timestamp'>   Yes
1    <class 'pandas._libs.tslibs.timestamps.Timestamp'>   Yes
2    <class 'float'>                                      No
3    NaN                                                  No
4    <class 'pandas._libs.tslibs.timestamps.Timestamp'>   Yes

尝试:

df_viz['col3']=(df_viz.col2.transform(lambda x:
  np.where(x==pd._libs.tslibs.timestamps.Timestamp,'Yes','No')))

您可以像这样检查每一行

df['check_datetime'] = [type(val) == datetime.datetime for val in df['datime_field']]

我不确定您的类型,可以通过(type(val))查找类型并将其放入代码中

如果您想要“是”和“否”

可以使用

df['my_col'] = np.where(df['my_col'] is True,"YES","NO)

我的尝试代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM