我有一个 [[[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() 循环遍历现有数据帧(仅将此列表作为一列),将值提取到单独的列表中,然后使用这些列表创建数据帧并将它们合并为列。与我的数据集上的其他操作相比,感觉效率不是很高,有没有办法使用内置方法来做到这一点?
尝试执行下面提到的代码,它应该可以工作 将 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)