首页 > 解决方案 > Python-使用列名获取Excel文件中特定单元格的值

问题描述

我想获取单元格的值取决于row_iterator(这只是一个迭代的数字)和列的名称(在这种情况下'Organization CRD#'

import os
import pandas as pd
import json

row_iterator = 0
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("output/{}.json".format(single_CRD), 'w') as json_file:
                
                data = {}
                data['header']=[]
                data['header'].append({
                'Organization CRD#':  '{}'.format(df.iloc[row_iterator,1])}) // here I want to change '1' to name of column which is 'Organization CRD#'
                row_iterator = row_iterator + 1
                break

你怎么能看到我的脚本是

  1. 从 python_files 文件夹中读取文件
  2. 然后它正在读取带有 CRD 编号的第二列,该编号返回一个 CRD 数组
  3. 然后循环 CRD 数组
  4. 在该循环中,它试图从特定单元格中获取值,在这里我想将列数更改为它的名称

我怎样才能做到这一点?

这里还有一点Excel 文件以便更好地理解...

在此处输入图像描述

标签: pythonexcelpandas

解决方案


好的,我想通了。

只需要和第二个标签.iloc

之后,带有格式的代码看起来像这样......

.format(df.iloc[row_iterator]['Organization CRD#']

而不是链索引,在索引中包含列名。

.format(df.loc[row_iterator,'Organization CRD#']

推荐阅读