通过Excel单元格索引访问Pandas数据框

时间:2020-02-04 00:17:38

标签: python excel pandas dataframe

我已将Excel电子表格导入到数据框中。我希望像访问Excel一样访问数据 参考:例如df.get(“ A1”)代替df.iloc [0,0]。通过Excel索引访问数据框数据是否已经存在一种不错的方法-类似于上面我虚构的get函数?

2 个答案:

答案 0 :(得分:1)

不是Pandas,而是xlswriter执行此操作:https://xlsxwriter.readthedocs.io/working_with_cell_notation.html

答案 1 :(得分:1)

您可以编写一个简单的函数来完成从Excel索引到数字索引的转换:

import regex as re

def index_transform(excel_index):
    match = re.match(r"^([a-z]+)(\d+)$", excel_index.lower())
    if not match:
        raise ValueError("Invalid index")

    x_cell = -1
    for idx, char in enumerate(match.group(1)[::-1]):
        x_cell += (26 ** idx) * (ord(char) - 96)  # ord('a') == 97

    y_cell = int(match.group(2)) - 1

    return y_cell, x_cell

# Usage
df.iloc[*index_transform("A1")]  # The * unpacks the returned tuple

# Example outputs
>>> index_transform("A1")
(0, 0)
>>> index_transform("E1")
(0, 4)
>>> index_transform("A5")
(4, 0)
>>> index_transform("e5")
(4, 4)
>>> index_transform("AA27")
(26, 26)
>>> index_transform("coffee1337")
(1336, 42608414)