我有数据框,我已将其转换为字典列表:
df = data.to_dict(orient = "records")
输出:
[{'MAIN KITCHEN': 9.6, 'Time': ' 05/01/2017 00:05:00'},
{'MAIN KITCHEN': 9.6, 'Time': ' 05/01/2017 00:10:00'},
{'MAIN KITCHEN': 9.6, 'Time': ' 05/01/2017 00:15:00'},
{'MAIN KITCHEN': 11.2, 'Time': ' 05/01/2017 00:20:00'},
{'MAIN KITCHEN': 11.2, 'Time': ' 05/01/2017 00:25:00'},
{'MAIN KITCHEN': 12.8, 'Time': ' 05/01/2017 00:30:00'},
{'MAIN KITCHEN': 9.6, 'Time': ' 05/01/2017 00:35:00'},
{'MAIN KITCHEN': 11.2, 'Time': ' 05/01/2017 00:40:00'},
{'MAIN KITCHEN': 12.8, 'Time': ' 05/01/2017 00:45:00'}]
P.S:我只想要这样的数据。
我想将此输出编码为url
或作为查询字符串。
我试过这个:
param = urllib.urlencode(df)
但是我收到了一个错误:
TypeError: not a valid non-string sequence or mapping object
有人可以告诉我这样做的正确方法吗?
答案 0 :(得分:0)
您需要遍历词典列表,并在每个词典上应用urllib.urlencode
。
In [46]: [urllib.urlencode(d) for d in df.to_dict(orient='records')]
Out[46]:
['Time=+05%2F01%2F2017+00%3A05%3A00&MAIN+KITCHEN=9.6',
'Time=+05%2F01%2F2017+00%3A10%3A00&MAIN+KITCHEN=9.6',
'Time=+05%2F01%2F2017+00%3A15%3A00&MAIN+KITCHEN=9.6',
'Time=+05%2F01%2F2017+00%3A20%3A00&MAIN+KITCHEN=11.2',
'Time=+05%2F01%2F2017+00%3A25%3A00&MAIN+KITCHEN=11.2',
'Time=+05%2F01%2F2017+00%3A30%3A00&MAIN+KITCHEN=12.8',
'Time=+05%2F01%2F2017+00%3A35%3A00&MAIN+KITCHEN=9.6',
'Time=+05%2F01%2F2017+00%3A40%3A00&MAIN+KITCHEN=11.2',
'Time=+05%2F01%2F2017+00%3A45%3A00&MAIN+KITCHEN=12.8']
您也可以在转换为字典之前执行此操作:
In [54]: df.apply(lambda x: urllib.urlencode(dict(x)), axis=1)
Out[54]:
0 Time=+05%2F01%2F2017+00%3A05%3A00&MAIN+KITCHEN...
1 Time=+05%2F01%2F2017+00%3A10%3A00&MAIN+KITCHEN...
2 Time=+05%2F01%2F2017+00%3A15%3A00&MAIN+KITCHEN...
3 Time=+05%2F01%2F2017+00%3A20%3A00&MAIN+KITCHEN...
4 Time=+05%2F01%2F2017+00%3A25%3A00&MAIN+KITCHEN...
5 Time=+05%2F01%2F2017+00%3A30%3A00&MAIN+KITCHEN...
6 Time=+05%2F01%2F2017+00%3A35%3A00&MAIN+KITCHEN...
7 Time=+05%2F01%2F2017+00%3A40%3A00&MAIN+KITCHEN...
8 Time=+05%2F01%2F2017+00%3A45%3A00&MAIN+KITCHEN...
dtype: object
In [55]: df.apply(lambda x: urllib.urlencode(dict(x)), axis=1).tolist()
Out[55]:
['Time=+05%2F01%2F2017+00%3A05%3A00&MAIN+KITCHEN=9.6',
'Time=+05%2F01%2F2017+00%3A10%3A00&MAIN+KITCHEN=9.6',
'Time=+05%2F01%2F2017+00%3A15%3A00&MAIN+KITCHEN=9.6',
'Time=+05%2F01%2F2017+00%3A20%3A00&MAIN+KITCHEN=11.2',
'Time=+05%2F01%2F2017+00%3A25%3A00&MAIN+KITCHEN=11.2',
'Time=+05%2F01%2F2017+00%3A30%3A00&MAIN+KITCHEN=12.8',
'Time=+05%2F01%2F2017+00%3A35%3A00&MAIN+KITCHEN=9.6',
'Time=+05%2F01%2F2017+00%3A40%3A00&MAIN+KITCHEN=11.2',
'Time=+05%2F01%2F2017+00%3A45%3A00&MAIN+KITCHEN=12.8']