拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 Python从TXT组织资料并写入csv

Python从TXT组织资料并写入csv

白鹭 - 2022-01-25 2097 0 0

我有这种格式的资料转储:

[
{
      "vaultId": "429d60edc11df0a576cd9173e8c0d0de8792538862db0122848b87a96ecdf537",
      "loanSchemeId": "MIN150",
      "ownerAddress": "df1q7crh6d3dscj3sajpklehpnwdwhvs0l0jm9fr7s",
      "state": "inLiquidation",
      "liquidationHeight": 1488540,
      "batchCount": 2,
      "liquidationPenalty": 5,
      "batches": [
        {
          "index": 0,
          "collaterals": [
            "282.34948388@DFI"
          ],
          "loan": "6.38045570@BABA"
        },
        {
          "index": 1,
          "collaterals": [
            "300.16175126@DFI"
          ],
          "loan": "0.26745972@GOOGL"
        }
      ]
    },
]
   

我已将其写入 txt,我正在尝试使用 Pandas 制作资料框,然后使用此代码写入 csv,但是我收到此错误ValueError: Length mismatch: Expected axis has 1729 elements, new values have 5 elements这是我用来形成资料框的代码,非常感谢。

import pandas as pd
import simplejson as json

df = pd.read_json('auctions.txt')
df[['index', 'collaterals', 'loan']] = df.batches.apply(pd.Series)

编辑:这是我更改代码的错误

    Traceback (most recent call last):
  File "c:\Users\iones\Documents\DeFI Chain Auction Bot\start.py", line 3, in <module>
    df = pd.read_json('auctions.json')
  File "C:\Users\iones\Documents\DeFI Chain Auction Bot\.venv\lib\site-packages\pandas\util\_decorators.py", line 207, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\iones\Documents\DeFI Chain Auction Bot\.venv\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\iones\Documents\DeFI Chain Auction Bot\.venv\lib\site-packages\pandas\io\json\_json.py", line 614, in read_json
    return json_reader.read()
  File "C:\Users\iones\Documents\DeFI Chain Auction Bot\.venv\lib\site-packages\pandas\io\json\_json.py", line 748, in read
    obj = self._get_object_parser(self.data)
  File "C:\Users\iones\Documents\DeFI Chain Auction Bot\.venv\lib\site-packages\pandas\io\json\_json.py", line 770, in _get_object_parser
    obj = FrameParser(json, **kwargs).parse()
  File "C:\Users\iones\Documents\DeFI Chain Auction Bot\.venv\lib\site-packages\pandas\io\json\_json.py", line 885, in parse
    self._parse_no_numpy()
  File "C:\Users\iones\Documents\DeFI Chain Auction Bot\.venv\lib\site-packages\pandas\io\json\_json.py", line 1140, in _parse_no_numpy
    loads(json, precise_float=self.precise_float), dtype=None
ValueError: Expected object or value

uj5u.com热心网友回复:

使用加载 JSON read_json,然后将批处理字典转换为列

import pandas as pd

df = pd.read_json('data.json')
df[['index', 'collaterals', 'loan']] = df.batches.apply(pd.Series)

如果您希望将抵押品放在不同的行中

df = df.explode('collaterals')

输出

print(df[['vaultId', 'liquidationHeight', 'index', 'collaterals', 'loan']])

                                             vaultId  liquidationHeight  index        collaterals              loan
0  6af21886adcb92c4669a8a901975eb9b9d5544c67e4292...            1489770      0  2326.00000000@DFI  2.24978028@GOOGL
1  6af21886adcb92c4669a8a901975eb9b9d5544c67e4292...            1489770      1  2326.00000000@DFI  2.24978028@GOOGL

编辑:

根据您所说的,看起来资料已损坏,即无效的 JSON 格式。请从源头上更正。我使用了以下资料样本。

{
  "vaultId": "6af21886adcb92c4669a8a901975eb9b9d5544c67e429267841491649810958a",
  "ownerAddress": "df1qhh9ek2d98mxjeh58xdsfj7ad2k7q4d4kwshsxr",
  "liquidationHeight": 1489770,
  "batchCount": 2,
  "batches": [
    {
      "index": 0,
      "collaterals": [
        "2326.00000000@DFI"
      ],
      "loan": "2.24978028@GOOGL"
    },
    {
      "index": 1,
      "collaterals": [
        "2326.00000000@DFI"
      ],
      "loan": "2.24978028@GOOGL"
    }
  ]
}

uj5u.com热心网友回复:

通过使用这个修复

def jsontocsv():
    df = pd.read_json('auctions.json')
    df = df.explode('batches')
    df[['index', 'collaterals', 'loan']] = df.batches.apply(pd.Series)
    print(df[['vaultId', 'liquidationHeight', 'index', 'collaterals','loan']])
    df.to_csv('auctions.csv')

`

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *