简体   繁体   English

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

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

I can check column types using df.dtypes , where df is pandas DataFrame. 我可以使用df.dtypes检查列类型,其中df是pandas DataFrame。 However, my question is a bit different. 但是,我的问题有点不同。 I have the following 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'>

The df["col2"].dtypes returns object . df["col2"].dtypes返回object

I need to create a new column is_timestamp that would check if col2 value is pandas timestamp. 我需要创建一个新列is_timestamp ,它将检查col2值是否为pandas时间戳。 For testing, I tried this code: 为了进行测试,我尝试了以下代码:

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

But it returns False . 但是它返回False

The expected output: 预期输出:

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

Try with: 尝试:

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

you can check for each row like this 您可以像这样检查每一行

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

I'm not sure about your type you can find your type by (type(val)) and place them into code 我不确定您的类型,可以通过(type(val))查找类型并将其放入代码中

if you want 'YES' and 'NO' 如果您想要“是”和“否”

can using 可以使用

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

my try code 我的尝试代码

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

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