gpt4 book ai didi

python - 将 Pandas 数据框转换为 csv

转载 作者:太空宇宙 更新时间:2023-11-04 05:21:52 26 4
gpt4 key购买 nike

enter image description here我有上面的数据框,我希望将其转换为 csv 文件。
我目前正在使用 df.to_csv('my_file.csv') 对其进行转换,但我想保留 3 个空白列。对于上面文件的行,我有以下过程。

dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'MainFile.csv')
with open(csvfilename, 'wb') as output_file:
writer = csv.writer(output_file, delimiter=',')
writer.writerow([])
writer.writerow(["","Amazon","Weekday","Weekend"])
writer.writerow(["","Ebay",wdvad,wevad])
writer.writerow(["","Kindle",wdmpv,wempv])
writer.writerow([])

我想在包含三个空白列的空白空间之后合并数据框。如何继续将数据框添加到现有的 csv 文件,以便我还可以在数据框之后添加更多包含数据的行。

最佳答案

考虑最初将数据帧输出到临时文件。然后,在创建 MainCSV 期间,读入临时文件,反复写入行,然后销毁临时文件。此外,在将数据帧写入 csv 之前,创建三个空白列。

下面假设您需要两个任务:1) 三个空白列和 2) 在 Amazon/Ebay/Kindle 行标题下方写入数据框值。示例数据使用随机正常值和标量值,wdvadwevadwdmpvwempv 是字符串文字他们的名字:

import csv, os
import pandas as pd

# TEMP DF CSV
dirname = os.path.dirname(os.path.abspath(__file__))
df = pd.DataFrame([np.random.normal(loc=3.0, scale=1.0, size=24)*1000 for i in range(7)],
index=['Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday'])
df['Blank1'], df['Blank2'], df['Blank3'] = None, None, None

df.to_csv(os.path.join(dirname, 'temp.csv')) # OUTPUT TEMP DF CSV

# MAIN CSV
csvfilename = os.path.join(dirname, 'MainFile.csv')
tempfile = os.path.join(dirname, 'temp.csv')

wdvad = 'wdvad'; wevad = 'wevad'; wdmpv = 'wdmpv'; wempv = 'wempv'

with open(csvfilename, 'w', newline='') as output_file:
writer = csv.writer(output_file)
writer.writerow([""])
writer.writerow(["","Amazon","Weekday","Weekend"])
writer.writerow(["","Ebay",wdvad,wevad])
writer.writerow(["","Kindle",wdmpv,wempv])
writer.writerow([""])

with open(tempfile, 'r') as data_file:
for line in data_file:
line = line.replace('\n', '')
row = line.split(",")
writer.writerow(row)

os.remove(tempfile) # DESTROY TEMP DF CSV

输出

CSV File Output

关于python - 将 Pandas 数据框转换为 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40041757/

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