簡體   English   中英

Pandas - 遍歷 dataframe 行並更新 df(一行代碼)

[英]Pandas - iterate over dataframe rows and update df (one line of code)

具有以下代碼。 場景描述:

遍歷具有 URL 列表的 dataframe 發送 GET 請求。 最初創建 3 個新列並根據上一個 get 請求的結果更新它們。

問題:是否有任何選項如何在一行代碼中編寫 3“df.set_value”?

提前謝謝了

import pandas as pd, numpy as np

d = {'ListOfURLs': ['URL1', 'URL2', 'URL3']}
df = pd.DataFrame(data=d)

#print(df)
s = requests.session()
s.post(login_url, login_data)
for index, row in df.iterrows():
    r = s.get(row['ListOfURLs'])
    r.status_code
    if r.status_code == 200:
        # Update Dataframe , create initially 3 new columns and update them based on the results from the previous get request
        df.set_value(index, 'Status Code', r.status_code)
        df.set_value(index, 'Result', '[OK]')
        df.set_value(index, 'Error', np.nan)

你可以這樣做:

import pandas as pd
import requests
import numpy as np

d = {'ListOfURLs': ['https://stackoverflow.com/q/65060875/4001592',
                    'https://stackoverflow.com/q/65060875/4001592',
                    'https://stackoverflow.com/q/65060875/4001592']}
df = pd.DataFrame(data=d)

for index, row in df.iterrows():
    r = requests.get(row['ListOfURLs'])
    if r.status_code == 200:
        df.at[index, ['Status Code', 'Result', 'Error']] = (r.status_code, '[OK]', np.nan)

print(df)

Output

                                     ListOfURLs  Status Code Result  Error
0  https://stackoverflow.com/q/65060875/4001592        200.0   [OK]    NaN
1  https://stackoverflow.com/q/65060875/4001592        200.0   [OK]    NaN
2  https://stackoverflow.com/q/65060875/4001592        200.0   [OK]    NaN

不要使用set_value

0.21.0 版后已棄用:改用.at[] 或.iat[] 訪問器。

請注意,原始問題中的一些細節被省略以生成實際的 output。

暫無
暫無

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

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