Python Pandas - 创建CSV并添加数据,而不是保存它



我构建了一个程序,可以进行一些数据分析,然后将其保存到桌面上的CSV中。

问题是,我的桌面路径中有我的名字,我不会知道使用它的任何其他人的路径(即它不起作用(。

有没有办法打开一个新的CSV并将数据插入其中(并让他们保存它(,而不是程序保存它?

我的代码是:

import pandas as pd
import pyodbc
d=[]
key1 = raw_input('enter a keyword to search for: ')
key2 = raw_input('enter another keyword to search for: ')

conn = pyodbc.connect('DSN=QueryBuilder')
cursor = conn.cursor()
stringQ ="SELECT GrantInformation.GrantRefNumber, GrantInformation.PIName, GrantInformation.Call, GrantInformation.RoutingClassification, GrantInformation.GrantCategory, GrantInformation.AuthorisationDate, GrantInformation.HoldingOrganisationName, GrantInformation.StatusGeneral, GrantInformation.GrantTitle, GrantSummary.Summary, GrantDates.ActualStartDate, GrantDates.ActualEndDate, GrantInformation.TotalGrantValue FROM (GrantInformation LEFT JOIN GrantSummary ON GrantInformation.GrantRefNumber = GrantSummary.GrantRefNumber) LEFT JOIN GrantDates ON GrantInformation.GrantRefNumber = GrantDates.GrantRefNumber WHERE (((GrantInformation.AuthorisationDate)>='2005/4/1') AND ((GrantInformation.StatusGeneral) Like '%auth%') AND ((GrantInformation.GrantTitle) Like '%{}%'AND (GrantInformation.TransferInd)= 'false' OR (GrantInformation.GrantTitle) Like '%{}%') AND ((GrantInformation.TransferInd)= 'false'))  OR (((GrantInformation.AuthorisationDate)>='2005/4/1') AND ((GrantInformation.StatusGeneral) Like '%auth%') AND ((GrantSummary.Summary) Like '%{}%'AND (GrantInformation.TransferInd)= 'false' OR (GrantSummary.Summary) Like '%{}%' AND (GrantInformation.TransferInd)= 'false'));".format(key1,key2,key1,key2)
cursor.execute(stringQ)
rows = cursor.fetchall()

for row in rows:
    d.append({'GrantRefNumber':row[0],'Call':row[2],'Classification':row[3],'Grant Category':row[4],'Authorisation Date':row[5],'Organisation':row[6],'Status General':row[7],'Grant Title':row[8],'Summary':row[9],'Start Date':row[10],'End Date':row[11],'Total Value':row[12]})
df = pd.DataFrame(d)
new_df = df[['GrantRefNumber','Grant Title','Organisation','Call','Grant Category','Authorisation Date','Status General','Total Value','Classification','Start Date','End Date','Summary']]
new_df.to_csv("C:/Users/nicholas/Desktop/data.csv", header=True, index=False, encoding='utf-8')

您可以使用动态路径:

保存到当前工作目录:

new_df.to_csv("data.csv", header=True, index=False, encoding='utf-8')

或使用os.getcwd()来控制目录:

import os
new_df.to_csv(os.getcwd()+"data.csv", header=True, index=False, encoding='utf-8')

相关内容

  • 没有找到相关文章

最新更新