简体   繁体   English

如何在python中根据月、年、时间列标题编写csv文件名

[英]How to write csv file name based on month, year, time column headers in python

This is probably an easy question for someone out there to answer.这对于外面的人来说可能是一个容易回答的问题。 I have a bunch of csv files that I would like to rename using info from within the file.我有一堆 csv 文件,我想使用文件中的信息重命名这些文件。

I have a data frame result that looks like this:我有一个如下所示的数据框result

              id  year  month  day  precip
0       pod_0001  2017      1    1     2.6
1       pod_0002  2017      1    1     0.4
2       pod_0003  2017      1    1     2.2
3       pod_0004  2017      1    1    25.2
4       pod_0005  2017      1    1    19.4

And I want the name of the file to be YYYY.MM.DD, so in this case it would look like result.2017.01.01.我希望文件名是 YYYY.MM.DD,所以在这种情况下它看起来像 result.2017.01.01。

How do I do that with the to_csv function like this one..?我如何使用像这样的to_csv函数来做到这一点..?

result.to_csv("result.csv", na_rep="0")

This solution may be somewhat old-schooled (it uses the % operator), but it works:这个解决方案可能有点老派(它使用%运算符),但它有效:

fname = "result.%04d.%02d.%02d.csv" % \
        tuple(result[['year','month','day']].drop_duplicates().values[0])
print(fname)
# result.2017.01.01.csv
result.to_csv(fname, na_rep="0")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM