[英]How to write to a header based on column name in csv with python
[英]How to write csv file name based on month, year, time column headers in python
這對於外面的人來說可能是一個容易回答的問題。 我有一堆 csv 文件,我想使用文件中的信息重命名這些文件。
我有一個如下所示的數據框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
我希望文件名是 YYYY.MM.DD,所以在這種情況下它看起來像 result.2017.01.01。
我如何使用像這樣的to_csv
函數來做到這一點..?
result.to_csv("result.csv", na_rep="0")
這個解決方案可能有點老派(它使用%
運算符),但它有效:
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.