3

我拼命地尝试使用 Pyxll 来编写一些获取一堆数组的 excel 函数,在 Python 中加载它们,将它们转换为 pandas DataFrames,稍微处理一下数据,然后返回最终的 DataFrame。现在,为了返回 DataFrame,我找到了pyxll 示例,但无论我如何尝试,我似乎都无法将加载的 excel 数组转换为我可以使用的 pandas DataFrames。

例如,我尝试使用下面的代码,但没有运气。也许如果我有某种方式知道 Python 中加载了什么以及它的外观,也许我有更好的机会了解如何操作数据,但我不知道如何在我的 Canopy 输出区域查看输出。

有谁知道将数据从 excel 导入到 python 的简单方法,对其进行处理然后将其返回到 excel,而无需保存文件,将其加载到 python 中,处理数据并覆盖现有文件?

@xl_func("string[] name, var[] day, string[] method, string[] currency, numpy_array amounts, date[] dates: dataframe")
def test(name, day, method, currency, amounts, dates):

df_name = DataFrame(name, columns = ['Name'])
    df_method = DataFrame(method, columns = ['Method']).ix[1:]
    df_currency = DataFrame(currency, columns = ['Currency']).ix[1:]


    df = df_name.join(df_method).join(df_currency)

    cols = ['Name', 'Currency', 'Method']
    df = df[cols]


return DataFrame(dates)
4

3 回答 3

4

PyXLL 可以使用自定义类型接受和返回 pandas 数据帧。

看看这个例子: https ://github.com/pyxll/pyxll-examples/blob/master/pandas

要查看输出,请查看日志文件。要在 Python 中使用 IPython 提示进行交互操作,请使用以下示例: https ://github.com/pyxll/pyxll-examples/tree/master/ipython

坚持使用函数而不是诉诸命名范围要好得多。

您也可以使用 PyXLL 注册键盘快捷键。有关自动调整数组公式输出大小的快捷方式,请参阅此示例: https ://github.com/pyxll/pyxll-examples/blob/master/shortcuts/resize_array_formula.py

如果您需要更多帮助,请联系支持人员以获得快速响应。

于 2014-11-12T20:27:58.437 回答
3

看看(我的)图书馆xlwings。它使来回发送 DataFrame 变得如此简单:

>>> from xlwings import Workbook, Range
>>> import pandas as pd
>>> wb = Workbook()  # Pass in the path of a file to work with an existing Workbook
>>> df = pd.DataFrame([[1., 2.], [3., 4.]], columns=['one', 'two'])
>>> Range('A1', index=False).value = df # send it over to Excel
>>> data = Range('A1').table.value  # read it back
>>> pd.DataFrame(data[1:], columns=data[0])
   one  two
0    1    2
1    3    4

请特别参阅有关DataFrames以及如何从VBA调用它的文档。

于 2014-09-25T23:00:37.217 回答
2

查看xlrd(Python 2 和 3)、xlwt(仅限 Python 2)和xlsxwriter(Python 2 和 3)模块以用于pandas. Pandas 在其代码中为它们提供了钩子;您可以在此处阅读有关read_excelto_excel功能的所有信息。

于 2014-09-25T21:58:42.617 回答