簡體   English   中英

遍歷 Pandas 中的行

[英]Iterating through rows in Pandas

我在將一些數學應用於我的 dataframe 時遇到問題

當前 df:

名稱 最后連接 查看
測試1 1647609274746 聯系
測試2 1647609274785 聯系
測試3 1647000000000 聯系
測試4 1647609274756 聯系

所需的 df:我現在想創建一個新列並檢查服務器是否仍然在線

名稱 最后連接 查看
測試1 1647609274746 聯系
測試2 1647609274785 聯系
測試3 1647000000000 無連接
測試4 1647609274756 聯系

當前代碼:

def checkServer():
        for index, row in df.iterrows():
                timeNow = int((time.time_ns) // 1000000)
                lastSeenTime = row['lastConnected']
                timeDifference = currentTime - lastSeenTime
                if timeDifference > 5000:
                        df['check'] = "No connection"
                else:
                        df['check'] = "Connection"
        return df

我的問題:

正如您在我當前的 dataframe 中看到的那樣,即使 test3 應該沒有連接,它也會為它們提供連接。 從我的故障排除中,我將 timeDifference 打印到每一行中,即使時間不同,我也得到了相同的時間差。 因此,我認為我的 for 循環可能是問題所在。

使用此站點以毫秒為單位獲取當前時間:currentmillis.com

我哪里錯了?

IIUC,不要使用iterrows ,而是使用矢量 function:

N = 5000
df.loc[df['lastConnected'].diff().lt(-N), 'check'] = 'No connection'

或者從頭開始創建列:

N = 5000
df['check'] = np.where(df['lastConnected'].diff().lt(-N),
                       'No connection', 'connection')

output:

    name  lastConnected          check
0  test1        1647609     Connection
1  test2        1647579     Connection
2  test3        1640009  No connection

也許你期望:

df['check'] = np.where(pd.Timestamp.today().timestamp() * 1000 - df['lastConnected'] > 5000,
                       'No connection', 'Connection')
print(df)

# Output
    name  lastConnected          check
0  test1  1647609274746     Connection
1  test2  1647609274785     Connection
2  test3  1647000000000  No connection
3  test4  1647609274756     Connection

舊答案

使用np.where

df['check'] = np.where(df['lastConnected'].diff().abs().gt(5000),
                       'No connection', 'Connection')
print(df)

# Output
    name  lastConnected          check
0  test1        1647609     Connection
1  test2        1647579     Connection
2  test3        1640009  No connection

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM