[英]In Pandas, how do I compare values in a dataframe with others in its row and column at the same time?
[英]How do I compare Time values in a pandas dataframe column to a defined time values?
我有一個 dataframe,它的時間值采用 24 小時格式,例如 06:55:07、20:09:42 等。如果值在上午 6:30 到下午 6:30 之間,我想將它們分類為白天,否則將其分類為晚上. 做這個的最好方式是什么? 這是我嘗試過的:
def datetimeToDayNight(column, daytime='06:30:00', nighttime='18:30:00'):
"""Convert datetime to string 'Day' or 'Night'."""
stringday= datetime.strptime(daytime, '%H:%M:%S').time()
stringnight = datetime.strptime(nighttime, '%H:%M:%S').time()
if (column > stringday & column > stringnight):
return 'Day'
else:
return 'Night'
df['Day_Night']= datetimeToDayNight(df['Time'])
I get the following error when I try this:
TypeError: Cannot perform 'rand_' with a dtyped [object] array and scalar of type [bool]
假設您有這個 dataframe(“時間”列是字符串):
Time
0 02:55:07
1 04:55:07
2 06:55:07
3 08:55:07
4 20:55:07
5 21:55:07
然后你可以使用Series.between
和np.where
:
df["Day_Night"] = np.where(
pd.to_timedelta(df["Time"]).between("06:30:00", "18:30:00"), "Day", "Night"
)
print(df)
印刷:
Time Day_Night
0 02:55:07 Night
1 04:55:07 Night
2 06:55:07 Day
3 08:55:07 Day
4 20:55:07 Night
5 21:55:07 Night
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.