问题
I can parse the following data. but I cannot show it as a table in columnar. How can I chart this?
for item in items:
print(item['symbol'])
[
{"symbol": "ZILUSDT", "positionAmt": "0", "entryPrice": "0.00000", "markPrice": "0.01728152", "unRealizedProfit": "0.00000000", "liquidationPrice": "0", "leverage": "20", "maxNotionalValue": "25000", "marginType": "cross", "isolatedMargin": "0.00000000", "isAutoAddMargin": "false", "positionSide": "SHORT"},
{"symbol": "FLMUSDT", "positionAmt": "0", "entryPrice": "0.0000", "markPrice": "0.00000000", "unRealizedProfit": "0.00000000", "liquidationPrice": "0", "leverage": "20", "maxNotionalValue": "25000", "marginType": "cross", "isolatedMargin": "0.00000000", "isAutoAddMargin": "false", "positionSide": "BOTH"},
{"symbol": "FLMUSDT", "positionAmt": "0", "entryPrice": "0.0000", "markPrice": "0.00000000", "unRealizedProfit": "0.00000000", "liquidationPrice": "0", "leverage": "20", "maxNotionalValue": "25000", "marginType": "cross", "isolatedMargin": "0.00000000", "isAutoAddMargin": "false", "positionSide": "LONG"},
{"symbol": "FLMUSDT", "positionAmt": "0", "entryPrice": "0.0000", "markPrice": "0.00000000", "unRealizedProfit": "0.00000000", "liquidationPrice": "0", "leverage": "20", "maxNotionalValue": "25000", "marginType": "cross", "isolatedMargin": "0.00000000", "isAutoAddMargin": "false", "positionSide": "SHORT"}
]
How can I show it in a table like the one below?
headers = ["Symbol", "EntryPrice", "side", "position"]
symbols = [x['symbol'] for x in data]
table = columnar(symbols, headers=headers)
print(table)
回答1:
You have a list of dictionaries. The easiest way is to wrap them into pandas' DataFrame, which handles that type out-of-the box.
import pandas as pd
tabulated = pd.DataFrame(items)
print(tabulated)
回答2:
Pandas is an excellent solution, but you can natively present data in table format too:
for row in zip(*([key] + (value) for key, value in sorted(items.items()))):
print(*row)
来源:https://stackoverflow.com/questions/64612074/tabulating-data-received-with-json-with-python