pandas - 将列表中的字典转换为 Pandas 中的行

标签 pandas dataframe

我目前有一个这样的数据框:

enter image description here

我想将“列表”列分解为行。我想使用字典中的键作为列名,所以理想情况下,我希望数据框看起来像这样:

eventId listingId currentPrice
103337923 1307675567 ...
103337923 1307675567 ...
103337923 1307675567 ...

这就是我得到的: print(listing_df.head(3).to_dict())

enter image description here

最佳答案

绝对应该有更好的方法来做到这一点。但这有效。 :)

df1 = pd.DataFrame(
    {"a": [1,2,3,4],
     "b": [5,6,7,8],
     "c": [[{"x": 17, "y": 18, "z": 19}, {"x": 27, "y": 28, "z": 29}],
           [{"x": 37, "y": 38, "z": 39}, {"x": 47, "y": 48, "z": 49}],
           [{"x": 57, "y": 58, "z": 59}, {"x": 27, "y": 68, "z": 69}],
           [{"x": 77, "y": 78, "z": 79}, {"x": 27, "y": 88, "z": 89}]]})

enter image description here

现在您可以从上面创建一个新的 DataFrame:
df2 = pd.DataFrame(columns=df1.columns)
df2_index = 0
for row in df1.iterrows():
    one_row = row[1]
    for list_value in row[1]["c"]:
        one_row["c"] = list_value
        df2.loc[df2_index] = one_row
        df2_index += 1

输出是您需要的方式:

enter image description here

现在我们已将列表扩展为单独的行,您可以使用以下命令将 json 进一步扩展为列:
df2[list(df2["c"].head(1).tolist()[0].keys())] = df2["c"].apply(
    lambda x: pd.Series([x[key] for key in x.keys()]))

enter image description here

希望能帮助到你!

关于pandas - 将列表中的字典转换为 Pandas 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48927032/

相关文章:

r - data.frame 中按组求和

python - Pandas 仅加入特定列

python - 将 Pandas Dataframe 行中的所有值相乘

python - 计算 pandas 中的高低

python - 如何计算列表列中列值的出现次数?

python - 基于列的 Pandas squash 数据框

python - Pandas iloc 不返回数据切片

python - Bokeh 不显示 Pandas 情节

python - 仅根据条件 python 加入

python - Pandas - 合并不同大小的数据帧