gpt4 book ai didi

python - Pandas -Python : How do you write new lines in Pandas?

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

我正在尝试使用 PandasAPI 的 GET 请求JSON 输出列表保存到 CSV 文件中> 但下面的代码仅生成单个条目,它不会创建新行。

示例 JSON 输出:

ID : 27980
Title : ELSVIOS 6 Colors Boho Split Long <font><b>Dress</b></font> Fashion Women O-Neck Maxi <font><b>Dress</b></font> Summer Short Sleeve Solid <font><b>Dress</b></font> With Belt Vestidos XS-3XL32815751265US
Price : $10.32US
Sale Price :$10.32
<小时/>
for resultsget in getlistproductsx:
producturls = resultsget['productTitle']
productids = resultsget['productId']
originalprices = resultsget['originalPrice']
saleprices = resultsget['salePrice']
print(producturls + str(productids) + originalprices + saleprices)
raw_data = {'product_title': [producturls],
'product_id': [productids],
'original_price': [originalprices],
'sale_price': [saleprices]}
df = pd.DataFrame(raw_data, columns = ['product_title', 'product_id', 'original_price', 'sale_price'])
df.to_csv('example2.csv')

最佳答案

正如 kosist 所说,您正在覆盖 CSV 文件。

创建第二个 DataFrame,您将在其中附加在循环中导入的数据。

import pandas as pd
cols = ['product_title', 'product_id', 'original_price', 'sale_price']
df = pd.DataFrame(columns=cols)

for resultsget in getlistproductsx:
producturls = resultsget['productTitle']
productids = resultsget['productId']
originalprices = resultsget['originalPrice']
saleprices = resultsget['salePrice']

print(producturls + str(productids) + originalprices + saleprices)
raw_data = {'product_title': [producturls],
'product_id': [productids],
'original_price': [originalprices],
'sale_price': [saleprices]}

# create second DataFrame to which the data is added
df2 = pd.DataFrame(raw_data, columns=cols)
# append the newly created DataFrame to the one keeping the data
df = df.append(df2)

# then write the DataFrame to csv
df.to_csv('csv.csv')

关于python - Pandas -Python : How do you write new lines in Pandas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53097922/

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