【问题标题】:How do I create a responsive excel document title using pandas?如何使用 pandas 创建响应式 Excel 文档标题?
【发布时间】:2019-08-19 15:30:41
【问题描述】:

所以,我已经成功构建了一个函数,我可以在其中收集一些数据,将其转换为数据框,然后将其转换为 Excel 文档。我遇到的问题是,我不知道如何创建响应式标题名称或存储位置。我有使用 pandas 硬编码的路径,如下所示:

developmentdata = pd.DataFrame(dev_names).to_excel(r'C:\Desktop\Dev\devproj\test.xlsx', header=False, index=False)

Excel 的标题为“test.xlsx”。我该怎么做才能解决这个问题?

【问题讨论】:

  • 你有你想要的标题作为变量吗?
  • 能够根据变量获取标题会很有用。例如,这些是我拥有的变量。 language = php location = boston 另外使用 time 模块中的 now 也很有用 理想情况下,我的标题应该类似于 boston_php_8192019。我只是不知道该怎么做

标签: python excel python-3.x pandas dataframe


【解决方案1】:

Python 为以编程方式构造文本字符串提供了许多不同的可能性。我个人推荐的一种现代方法是使用f-strings。构造和格式化日期也有许多不同的可能性,但我认为 python 的 datetime 模块应该适合您的需要。举个例子:

from datetime import datetime

# Variables with identifying information
output_dir = r"C:\Desktop\Dev\devproj"
language = "php"
location = "boston"

# Retrieve current date as a formatted string
current_date = datetime.now().strftime("%Y%m%d")

# Construct output path using f-strings
file_name = f"{location}_{language}_{current_date}.xlsx"
output_path = rf"{output_dir}\{file_name}"

print(output_path)
# Output:
# C:\Desktop\Dev\devproj\boston_php_20190821.xlsx

注意 1:要使用 f 字符串,您必须具有 python 3.6 或更高版本。

注意 2:对于文件名中的日期,我始终建议使用“年-月-日”格式(如代码示例中所做的那样)。这样做的好处是,当您按名称对这些文件中的多个文件进行排序时,您也会自动获得正确的时间排序。

【讨论】:

  • 我创建了一个最终有效的方法,但我喜欢这个。谢谢你的回答。我打算对 f 弦进行更多研究,因为我才刚刚开始听说它们,但它们似乎很有用。
猜你喜欢
  • 2018-10-16
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 2020-07-07
  • 2019-02-01
  • 2018-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多