我使用一個名為emails_visits:pandas的資料框被匯入
Rep Doctor Date type
0 1 1 2021-01-25 email
1 1 1 2021-05-29 email
2 1 2 2021-03-15 email
3 1 2 2021-04-02 email
4 1 2 2021-04-29 email
30 1 2 2021-06-01 visit
5 1 3 2021-01-01 email
我想根據列型別中的值創建列“date_after”,如果它等于“訪問”我想從列“日期”中查看日期,否則為空。
我使用這段代碼:
emails_visits["date_after"]=np.where(emails_visits["type"]=="visit",emails_visits["Date"],np.nan)
但是,它會引發錯誤:
emails_visits["date_after"]=np.where(emails_visits["type"]=="visit",emails_visits["Date"],np.nan)
File "<__array_function__ internals>", line 5, in where
TypeError: The DType <class 'numpy.dtype[datetime64]'> could not be promoted by <class 'numpy.dtype[float64]'>. This means that no common DType exists for the given inputs. For example they cannot be stored in a single array unless the dtype is `object`. The full list of DTypes is: (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[float64]'>)
我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
如果你愿意,你可以這樣做。
email_visits['date after'] = email_visits.apply(lambda x: x[2] if x[3] == 'visit' else '', axis=1)
uj5u.com熱心網友回復:
型別datetime64列Date的emails_visits是與一個不兼容np.nan這是一個np.float64。由于您似乎使用 Pandas,因此您需要使用pd.NA它來代替缺失值(雖然np.nan意味著該值不是數字,并且僅適用于浮點數)。其實這里最好不要用np.wherepandas functions。這是一個簡單的解決方案:
emails_visits["date_after"] = emails_visits["Date"].where(emails_visits["type"]=="visit")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/409866.html
標籤:
上一篇:pandasgroupby計算groupby列的百分比
下一篇:熊貓,調整列標題的高度?
