首页 > 解决方案 > Pandas-Python:如何在 Pandas 中编写新行?

问题描述

我正在尝试将JSON输出列表保存API's GET requestsCSV文件中,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')

标签: pythonjsonpandas

解决方案


正如 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')

推荐阅读