简体   繁体   中英

How to check a type of column values in pandas DataFrame

I can check column types using df.dtypes , where df is pandas DataFrame. However, my question is a bit different. I have the following 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 .

I need to create a new column is_timestamp that would check if col2 value is pandas timestamp. For testing, I tried this code:

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

But it returns 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

if you want 'YES' and 'NO'

can using

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

my try code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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