簡體   English   中英

Python - 使用 Pandas 遍歷 excel 文件的行

[英]Python - Iterating through rows of excel files with Pandas

我在遍歷excel 文件中的行時遇到問題。

import os
import pandas as pd
import json

for file in os.listdir("./python_files"):
    if file.endswith(".xlsx"):
        df = pd.read_excel(os.path.join("./python_files", file)) 
        CRD_Array = df.iloc[:,1].values
        for single_CRD in CRD_Array:           
            with open("{}.json".format(single_CRD), 'w') as json_file:
                row_iterator = 0
                data = {}
                data['header']=[]
                data['header'].append({'Organization CRD#':  '{}'.format(df.iloc[row_iterator,1])})
                json.dump(data, json_file)
                row_iterator = row_iterator + 1
  

          

你怎么能看到我的腳本是

  1. python_files文件夾中讀取文件
  2. 然后它正在讀取帶有CRD編號的第二列,該編號返回一個CRDs數組
  3. 然后循環CRD數組
  4. 在那個循環中它試圖用“hedar”字段保存.json文件

我現在在 output 得到什么

文件名172081.json

{"header": [{"Organization CRD#": "172081"}

文件名534123.json

{"header": [{"Organization CRD#": "172081"}

文件名184521.json

{"header": [{"Organization CRD#": "172081"}

我看起來像df.iloc [row_iterator, 1]沒有改變行屬性,盡管為每個循環重復添加了 +1

有人可以幫忙嗎?

編輯:Excel 文件示例-

在此處輸入圖像描述

我想要達到的目標

文件名172081.json

{"header": [{"Organization CRD#": "172081"}

文件名534123.json

{"header": [{"Organization CRD#": "534123"}

文件名184521.json

{"header": [{"Organization CRD#": "184521"} 

在 for 循環中,您正在增加 row_iterator,但在打開后的第一行中,您始終將其設置回 0。您需要將該行從循環中取出。 像這樣:

row_iterator = 0

for single_CRD in CRD_Array: 
          
    with open("{}.json".format(single_CRD), 'w') as json_file:
       data = {}
       data['header']=[]
       data['header'].append({'Organization CRD#': '{}'.format(df.iloc[row_iterator,1])})
       json.dump(data, json_file)
       row_iterator = row_iterator + 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM