首页 > 解决方案 > 将熊猫数据框导出到 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 这是 df 在 1000 个记录周期内的输出。

[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...

标签: pythonpandascsv

解决方案


如果您可以使用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)

或者,您仍然可以使用光标。但是,您需要在构建数据框之前将提取的行拆分为单独的部分。目前,具有多个数据库表列的整行被放入单个数据框行中。


推荐阅读