一方面,我们有这个熊猫数据帧:
import pandas as pd
df = {"EventName":{"0":"Event234","1":"Event235","2":"Event236"},"EventType":{"0":"TypeA","1":"TypeA","2":"TypeB"},"Data1":{"0":"Data266276","1":"Data266277","2":"Data266278"},"Data2":{"0":"Data432562","1":"Data432563","2":"Data432564"}}
df = pd.DataFrame(df)
print(df)
返回这个:
EventName EventType Data1 Data2
0 Event234 TypeA Data266276 Data432562
1 Event235 TypeA Data266277 Data432563
2 Event236 TypeB Data266278 Data432564
另一方面,我们有以下函数,它发送一个 POST 请求:
import time
import requests
# Test post url calls
# https://stackoverflow.com/questions/5725430/http-test-server-that-accepts-get-post-calls
AlertURL = "http://httpbin.org/anything"
def alert(msg):
nowdt = time.strftime("%m/%d/%Y %H:%M:%S")
payload = {"msg": str(nowdt)+", "+msg}
response = requests.post(AlertURL, payload)
print(response.text)
alert(df.EventName+" "+df.EventType+" "+df.Data1+" "+df.Data2)
最后一行是发送一 (1( 个包含所有数据帧行的请求。
我们希望每个数据帧行发送一个请求(在本例中为三个(, 它们之间有 2 秒的延迟。
我们怎么做?
使用带有数据帧形状的 for 循环来循环遍历每一行。 使用 i 指定要发送的行。最后用时间睡觉来等待。
for i in range(df.shape[0]):
alert(df.EventName[i]+" "+df.EventType[i]+" "+df.Data1[i]+" "+df.Data2[i])
time.sleep(2)
您可以使用 iterrows(( ti 迭代数据帧和 time.sleep(( 以或多或少确定的方式等待一段时间:
for index, row in df.iterrows():
alert(row['EventName']+" "+row['EventType']+" "+row['Data1']+" "+row['Data2'])
time.sleep(2) #2 seconds
如果您愿意,可以移动警报函数中的睡眠指令靠近请求,以便清楚起见。
for row in df.iterrows():
alert(row[0] + " " + row[1] + " " + row[2] + " " + row[3])
time.sleep(2)