[英]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
你怎么能看到我的腳本是
python_files
文件夾中讀取文件CRD
編號的第二列,該編號返回一個CRDs
數組CRD
數組.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.