亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據不同列的值對數據框執行查找

根據不同列的值對數據框執行查找

嚕嚕噠 2022-06-28 16:49:53
有這樣的數據框 -df = {'Request': [0, 0, 1, 0, 1, 0, 0], 'Time': ['16:00', '17:00', '18:00', '19:00', '20:00', '20:30', '24:00'], 'grant': [3, 0, 0, 5, 0, 0, 5]}pd.DataFrame(df).set_index('Time')    Out[16]:        Request  grantTime                 16:00        0      317:00        0      018:00        1      019:00        0      520:00        1      020:30        0      024:00        0      5“請求”列中的值是布爾值,表示是否提出了請求。1 = 請求 0 = 無請求?!笆谟琛绷兄械闹当硎境跏际谟璐笮 N蚁胗嬎忝總€請求的請求和授權之間的時間。所以在這種情況下,他們將是 19:00 - 18:00 = 1 小時和 24:00-20:00 = 4 小時。有沒有辦法使用 pandas 輕松地對大型數據集執行此操作?
查看完整描述

2 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

我會這樣做:


df = {'Request': [0, 0, 1, 0, 1, 0, 0],

     'Time': ['16:00', '17:00', '18:00', '19:00', '20:00', '20:30', '24:00'],

     'grant': [3, 0, 0, 5, 0, 0, 5]}


df = pd.DataFrame(df) #create DataFrame


#get rid of any rows have neither a grant nor request

df = df[(df[['grant', 'Request']].T != 0).any()] 


#change the time in HH:MM to number of minutes

df['Time'] = df['Time'].str.split(":").apply(lambda x: int(x[0])*60 + int(x[1]))


#get the difference between those times

df['timeElapsed'] = df['Time'].diff()


#filter out the requests to only get the grants and their times. 

#Also, drop the NA from the first line.

df = df[(df[['grant']].T != 0).any()].dropna()


#drop all columns except timeElapsed and Grant

df = df[['timeElapsed', 'grant']]

那么輸出看起來像這樣,timeElaped 以分鐘為單位:


   timeElapsed  grant

3         60.0      5

6        240.0      5


查看完整回答
反對 回復 2022-06-28
?
一只斗牛犬

TA貢獻1784條經驗 獲得超2個贊

您首先需要將您的Time索引轉換為可減去的東西以找到時間增量。使用pd.to_timestamp不起作用,因為沒有24:00. 下面的解決方案使用十進制時間(1:30PM = 13.5):


# Convert the index into decimal time

df.index = pd.to_timedelta(df.index + ':00') / pd.Timedelta(hours=1)


# Get time when each request was made

r = df[df['Request'] != 0].index.to_series()


# Get time where each grant was made

g = df[df['grant'] != 0].index.to_series()


# `asof` mean "get the last available value in `r` as the in `g.index`

tmp = r.asof(g)

df['Delta'] = tmp.index - tmp

結果:


      Request  grant  Delta

Time                       

16.0        0      3    NaN

17.0        0      0    NaN

18.0        1      0    NaN

19.0        0      5    1.0

20.0        1      0    NaN

20.5        0      0    NaN

24.0        0      5    4.0


查看完整回答
反對 回復 2022-06-28
  • 2 回答
  • 0 關注
  • 98 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號