python - Pandas-Python:如何在 Pandas 中编写新行?
问题描述
我正在尝试将JSON
输出列表保存API's GET requests
到CSV
文件中,Pandas
但下面的代码只生成单个条目,它不会创建新行。
示例 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')
推荐阅读
- r - 一次从变量中删除一个数据元素(值)并在 R 中执行函数
- python - 如何将字典写入 CSV 文件?
- ios - 一个带有按钮的 ViewController 中的多个音频文件
- r - 如何对由家庭 ID 链接的变量的多行值求和
- excel - 如何在 VBA 中格式化和连接具有不同范围的发票或银行对账单
- discord.js - How to use pm2 to autorestart my discord bot
- node.js - 数据存储模拟器创建空 index.yaml - 远程 Firebase 会引发错误,而本地不会
- node.js - 使用 mosca MQTT 的请求响应模式
- algorithm - 从 PEG 语法生成正确的短语
- javascript - 如何使撤消和重做与我的文本同步解决方案一起使用?