gpt4 book ai didi

python - 将 pandas 数据框导出为 CSV

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:35 24 4
gpt4 key购买 nike

我正在将 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...

最佳答案

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

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

关于python - 将 pandas 数据框导出为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54497443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com