0

尝试使用 pandas read_fwf,但在我的情况下,我在 json 中有名为 position 的起始位置,并且 column-size 具有大小,我想使用来自 flatfile 的填充值到来自同一位置的多个列。下面是示例 json 和平面文件以及预期输出。

示例 Json:

          "copybook": {
          "item": [
        {
          "column-size": 3,
          "position": 1,
          "column-name": "SAMPLE_1",
          "column-type": "STRING"
        },
        {
          "column-size": 3,
          "position": 4,
          "column-name": "COL_2",
          "column-type": "STRING"
        },
        {
          "redefines": "COL_2",
          "item": [
          {
            "column-size": 2,
            "position": 4,
            "column-name": "COL_3",
            "column-type": "INT"
          },
          {
            "column-size": 1,
            "position": 6,
            "column-name": "COL_4",
            "column-type": "STRING"
          }
        ]
      }
    ]
  }
}```
 
Sample Data is CCCRRR
    
expected output is 
    
SAMPLEE_1 COL_2 COL_3 COL_4
CCC       RRR   RR    R
4

1 回答 1

0

假设样本数据是 ABCDEF。如果你想要 ABC/DEF/int(DE)/F,你可以这样做:

df = pd.read_fwf('filename', widths=[3,3], header=None)
df.columns = ['SAMPLE_1', 'COL_2']
df['COL_3'] = df['COL_2'].str[:2].astype(int)
df['COL_4'] = df['COL_2'].str[-1]

注意。我假设没有标题,但如果这不正确,请更改代码

于 2021-08-10T06:03:57.803 回答