pandas 中是否有一个函数可以让您高效地为字典键+值对创建列?

问题描述 投票:0回答:1

我有一个 [[[key1,value1],[key2,value2],...,500],...,n] 形式的列表 - 又名具有 500 个级别的 L2 订单数据。 我想将此列表转换为数据框,其中包含列 key_1,...,key_500 和 value_1,...,value_500。 - 每个级别都有价格 + 交易量列的数据框(例如 level_1_volume、level_2_volume、...、level_500_volume)

我当前的解决方案只是使用 df.iterrows() 循环遍历现有数据帧(仅将此列表作为一列),将值提取到单独的列表中,然后使用这些列表创建数据帧并将它们合并为列。与我的数据集上的其他操作相比,感觉效率不是很高,有没有办法使用内置方法来做到这一点?

python pandas dictionary
1个回答
0
投票

尝试执行下面提到的代码,它应该可以工作 将 pandas 导入为 pd

# Your list of lists
data = [['key1', 'value1'],
        ['key2', 'value2'],
        ['key3', 'value3'],
        ['key4', 'value4']]

# Convert the list of lists into a dataframe
df = pd.DataFrame(data, columns=['Key', 'Value'])

# Display the original dataframe
print("Original DataFrame:")
print(df)

# Reshape the dataframe by setting the 'Key' column as the index
df.set_index('Key', inplace=True)

# Transpose the dataframe to convert keys into columns
df = df.T

# Reset the index to have numeric index
df.reset_index(drop=True, inplace=True)

# Display the final dataframe
print("\nFinal DataFrame:")
print(df)
© www.soinside.com 2019 - 2024. All rights reserved.