-1

我是一名基本的 Python 程序员。我正在使用 python3 并尝试将元素添加到字典列表中。我想向列表的每个字典添加不同的元素。我尝试使用 append()、add() 和 insert,但糟糕的是我没有找到任何运气。这是我的代码和下面的预期输出。

code :-
dataframe = spark.read.option("header", True).option("inferschema", True).csv("order_details.csv") 
data = ks.DataFrame(dataframe) #converted to koalas
stats = data.describe()
stats_result = json.loads(stats.to_json())
stats_result["statsresult"] = "count" #trying to add new field 

error :-
TypeError: list indices must be integers or slices, not str

output :- 
{
[
    {
        "discount": 10.0,
        "orderID": 10.0,
        "productID": 10.0,
        "quantity": 10.0,
        "unitPrice": 10.0
    },
    {
        "discount": 0.0,
        "orderID": 10249.4,
        "productID": 42.6,
        "quantity": 15.7,
        "unitPrice": 22.0
    },
    {
        "discount": 0.0,
        "orderID": 1.1737877908,
        "productID": 20.9719389238,
        "quantity": 12.000462954,
        "unitPrice": 12.7714960404
    }
    ]
    }


Expected output:-
             {
             [
             {
         "discount": 1000,
         "orderID": 1000,
         "productID": 1000,
         "quantity": 1000,
         "statsresult": "count",
         "unitPrice": 1000
          },
          { 
         "discount": "0",
         "orderID": "10625",
         "productID": "9",
         "quantity": "90",
         "statsresult": "max",
         "unitPrice": "99"
          },
          {
         "discount": "0",
         "orderID": "10248",
         "productID": "1",
         "quantity": "1",
         "statsresult": "min",
         "unitPrice": "10"
          }
          ]
          }

任何帮助是极大的赞赏!谢谢 :)

4

1 回答 1

1
for element in stats_result:
  # calculate value to insert
  element["key"] = some_value
于 2021-06-11T06:29:19.947 回答