将输入api数据附加到pandas dataframe,我的函数有什么问题?

2024-06-26 17:45:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在接收一个api数据“nftp”的提要,我有一个处理传入数据的函数。我收到的数据正常,我可以打印数据(根据下面的功能)

如何将数据存储在数据框中

数据“nftp”是流式传输的,即每次新的一行或有时几行同时进入时,“nftpGeneralHandler”应该将数据附加到数据帧,而不是以空数据帧开始,只有一个空列表(我猜)

传入数据格式: [386,3375,'OSE','S?',94520,'STL',94520800,36.2,'A','S','S',0.0,'S'] 我的函数中的Print命令返回:('STL',94520,36.2,1145,'A','S')

当我试图将数据存储在列表中,然后是数据帧中时,我做错了什么

graph_data = pd.DataFrame()
def nftpGeneralHandler(nftp, api): 
   print "Received ", nftp
   data_list = []
   if nftp[1] == 3 and nftp[10] == 'A':
       print (nftp[6], nftp[7], nftp[9], nftp[8], nftp[10], nftp[14])
       data_list.append([nftp[6], nftp[7], nftp[9], nftp[8], nftp[10], nftp[14]])
       graph_data.append(data_list)

   elif nftp[1] == 99: 
      nftpError(nftp, api)

Tags: 数据函数功能api列表data流式list
1条回答
网友
1楼 · 发布于 2024-06-26 17:45:00

我认为您可以在函数的每个循环中返回所需的数据,并将它们附加到graph_data。上次使用DataFrame构造函数:

def nftpGeneralHandler(nftp, api): 
   #print "Received ", nftp
   if nftp[1] == 3 and nftp[10] == 'A':
       print (nftp[6], nftp[7], nftp[9], nftp[8], nftp[10], nftp[14])
       out = [nftp[6], nftp[7], nftp[9], nftp[8], nftp[10], nftp[14]]
   elif nftp[1] == 99: 
      nftpError(nftp, api)
   return out

L1 = [386, 3, 375, 'OSE', '?', 94520, 'STL', 94520, 800, 36.2, 'A', '?', '?', 0.0, 'S'] 
L2 = [386, 3, 375, 'OSE', '?', 94520, 'STL', 94520, 800, 36.2, 'A', '?', '?', 0.0, 'S'] 
L3 = [386, 3, 375, 'OSE', '?', 94520, 'STL', 94520, 800, 36.2, 'A', '?', '?', 0.0, 'S'] 
api = ''    
graph_data = []

for L in [L1, L2, L3] :
    graph_data.append(nftpGeneralHandler(L,api))
print (graph_data)
[['STL', 94520, 36.2, 800, 'A', 'S'], 
 ['STL', 94520, 36.2, 800, 'A', 'S'], 
 ['STL', 94520, 36.2, 800, 'A', 'S']]

print (pd.DataFrame(graph_data))
     0      1     2    3  4  5
0  STL  94520  36.2  800  A  S
1  STL  94520  36.2  800  A  S
2  STL  94520  36.2  800  A  S

相关问题 更多 >