简体   繁体   English

使用 Output 路径将 Dataframe + 动态文件名写入 CSV

[英]Write Dataframe + Dynamic Filename to CSV with Output Path

i know that the answer is simple and out there somewhere but i cannot seem to find it.我知道答案很简单,而且在某个地方,但我似乎找不到。 As my title suggests, I am trying to write a pandas DF with a dynamic filename in.csv format to an output directory given a path.正如我的标题所暗示的那样,我正在尝试将具有动态文件名的 pandas DF 格式为 csv 格式,并在给定路径的 output 目录中。 Here below is my error code below.下面是我的错误代码。 Thank you for any suggestions and I'm open to doing this a different or pythonic way if possible.感谢您的任何建议,如果可能的话,我愿意以不同的或 Python 的方式来做这件事。

runfile('C:/Users/U321103/.spyder-py3/Read_VORTEX_test_files.py', wdir='C:/Users/U321103/.spyder- 
py3')
klondikeii.Vortex_WIND.csv
Traceback (most recent call last):
File "C:\Users\U321103\.spyder-py3\Read_VORTEX_test_files.py", line 29, in <module>
c.to_csv(Path(p + filename ), index=False)
TypeError: unsupported operand type(s) for +: 'WindowsPath' and 'str'

My code looks like this:我的代码如下所示:

from sys import exit
import pandas as pd
from pathlib import Path

# Create a dataframe from csv
df = pd.read_csv("\\\porfiler03\\gtdshare\\VORTEX\\VALIDATION\\vortex_links.txt", delimiter=',')
# User list comprehension to create a list of lists from Dataframe rows
list_of_rows = [list(row) for row in df.values]
# Print list of lists i.e. rows
#print(list_of_rows)

var = df.variable.to_frame() #extract wind or power from df 'variable' column
#Find farm_data = farm_vortex cases
#for k in range(0,len(df)):
for k in range(0,1):
  if (( df.farm_data[k] == df.farm_vortex[k]) and var.variable[k] == 'wind'):
    #print('chinook = vortex data')
    c = pd.read_csv(df.link[k])#dataframe with vortex wind data
    filename = df.farm_data[k] + '.' + 'Vortex_WIND' + '.csv'
    print(filename)
    #save the data to a csv_file.
    p = Path('///porfiler03//gtdshare//')
    c.to_csv(Path(p + filename ), index=False)
exit()

Remove Path() from '///porfiler03//gtdshare//'.从 '///porfiler03//gtdshare//' 中删除 Path()。

In p + filename you are trying to concatenate to create the full path.在 p + filename 中,您尝试连接以创建完整路径。 You can do so for two strings but not for a string and a path, and this is what the error is telling you.您可以对两个字符串执行此操作,但不能对一个字符串和一个路径执行此操作,这就是错误告诉您的内容。 Try:尝试:

p = '///porfiler03//gtdshare//'
c.to_csv(Path(p + filename ), index=False)

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

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