[英]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.