【问题标题】:Python Pandas - Creating a CSV and adding the data, rather than saving itPython Pandas - 创建 CSV 并添加数据,而不是保存数据
【发布时间】:2017-11-23 02:10:21
【问题描述】:

我已经构建了一个程序,它可以进行一些数据分析,然后将其保存到我桌面上的 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')

【问题讨论】:

    标签: python csv pandas path


    【解决方案1】:

    您可以使用动态路径:

    要么保存到您当前的工作目录:

    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')
    

    【讨论】:

    • 太棒了,谢谢!! :)... 没想到这么简单
    猜你喜欢
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 2018-10-14
    • 2022-08-12
    • 2019-06-04
    • 2018-11-25
    相关资源
    最近更新 更多