将熊猫数据框导出为CSV

时间:2019-02-02 20:57:41

标签: python pandas csv

我正在将SQL表加载到数据框中,然后将其直接推入CSV中。问题是出口。我需要:

value|value|value

我得到:

"(value|value|value)"

我如何说了出来?

这是我的代码:

for row in self.roster.itertuples():
    SQL = self.GenerateSQL(row)
    self.filename = '{}_{}.csv'.format(row.tablename, now.strftime("%Y-%m-%d"))
    # Open the file
    f = open(os.path.join(self.path, self.filename), 'w')
    # Create a connection and get a cursor
    cursor = self.conn.cursor()
    # Execute the query
    cursor.execute(SQL)
    # Get data in batches
    rowcount = 0
    while True:
        # Read the data
        df = pd.DataFrame(cursor.fetchmany(1000))
        # We are done if there are no data
        if len(df) == 0:
            break
        # Let's write to the file
        else:
            rowcount += len(df.index)
            print('Number of rows exported: {}'.format(str(rowcount)))
            df.to_csv(f, header=False, sep='|', index=False)

    # Clean up
    f.close()
    cursor.close()

赞赏任何见识。

更新#1 这是1000个记录周期内df的输出。

[1000 rows x 1 columns]
Number of rows exported: 10000
                                                     0
0    [11054, Smart Session (30 Minute) , smartsessi...
1    [11055, Best Practices, bestpractices, 2018-06...
2    [11056, Smart Session (30 Minute) , smartsessi...
3    [11057, Best Practices, bestpractices, 2018-06...

两个记录:

                                                   0
0  [1, Offrs.com Live Training, livetraining, 201...
1  [2, Offrs.com Live Training, livetraining, 201...

1 个答案:

答案 0 :(得分:0)

假设您可以使用sqlalchemy程序包,则可以利用pd.read_sql函数来处理查询数据库和检索数据。

import pandas as pd
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres@localhost:5432/sample')

df = pd.read_sql_query('select * from climate limit 3',con=engine)
df.to_csv('out.csv', header=False, sep='|', index=False)

或者,您仍然可以使用光标。但是,您需要在构造数据帧之前将提取的行拆分为单独的片段。目前,全行与多个数据库表列放入单个数据帧的行。

相关问题