[英]Exporting pandas dataframe to 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()
贊賞任何見識。
UPDATE#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...
只要您可以使用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)
或者,您仍然可以使用光標。 但是,您需要在構造數據幀之前將提取的行拆分為單獨的片段。 當前,具有多個數據庫表列的整個行都放在單個數據框行中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.