我有每个州学校的数据集。我想按州对学校进行分组,运行一些计算来创建排名,然后将每个排名导出到名为“state.xlsx”的单独 .xlsx 文件。例如,AK学校数据放入ranking_alaska.xlsx,TX学校数据放入ranking_texas.xlsx等。
此处的示例数据:https://docs.google.com/spreadsheets/d/1-wdmIz_-AILcBqzvpwAFGZfXqhq8oDRrYFVVdkjZ10o/edit?usp=sharing
我尝试将状态字段连接到文件名上,但出现 TypeError: can only concatenate str (not "tuple") to str。当我使用静态文件名运行代码时,它会为第一行数据中的状态创建一个文件。
df = pd.read_excel("ranker_test.xlsx", sheet_name='DATA')
grouped = df.groupby('state')
for x in grouped:
df.to_excel('test files/ranking_' + x + '.xlsx', index=False)
我想将其余代码添加到 for 循环中并使文件名动态化,以便在运行时生成 50 个州排名 excel 文件,每个文件都以各自的州命名。
编辑: 我已使用 Reedinator 的输入来创建文件名,但在将每个组导出到 Excel 时遇到问题。它要么将所有组的整个数据帧返回到每个文件,要么无法执行。这是我的代码:
for group in grouped:
group.to_frame().to_excel('test files/ranking_{}.xlsx'.format(group[0]), index=False)
但我得到 AttributeError: 'tuple' object has no attribute 'to_frame'
如何将元组转换为 DataFrame 以发送到 Excel?
最佳答案
这个错误告诉你一个非常简单的解释为什么它不起作用 -> x
是一个元组并且不是一个字符串!就我个人而言,我会尝试打印它并验证它确实是我想要的:
for x in grouped:
print(x)
这将显示类似 (item0, item1, item2, ..., itemN)
现在您可以选择哪个项目是您要查找的字符串,例如:
for x in grouped:
df.to_excel('test files/ranking_{}.xlsx'.format(x[0]), index=False)
其中x[0]
将告诉它获取item0
(理想情况下是一个字符串,但您也可以将其转换为一个,如下所示)。或者,您可以创建一个类似 test files/ranking_(item0, item1, item2, ..., itemN).xlsx
的文件名(使用元组的字符串表示形式),其中包含以下内容:
for x in grouped:
df.to_excel('test files/ranking_{}.xlsx'.format(x), index=False)
应该注意的是,.format()
方法在需要时隐式调用 str()
函数(因为 .format()
is different than concatenation and is usually a lot cleaner to read, faster to run, and just generally better 而不是串联)。如果您真的想使用连接,您只需自己将其设为字符串即可:
for x in grouped:
df.to_excel('test files/ranking_' + str(x) + '.xlsx', index=False)
但是请转换到.format()
!!如果您有较新版本的 python,您甚至可以跳到最新最好的 f strings
您似乎还应该查看 pandas
groupby function
他们的例子让我相信你需要:
for name, group in grouped:
group.to_excel('test files/ranking_{}.xlsx'.format(name), index=False)
但是,我不是 pandas
专家,也没有测试过它的准确性。
关于python - 如何根据PANDAS中的groupby字段在for循环中写入to_excel动态文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56467820/