【发布时间】:2021-05-12 13:39:48
【问题描述】:
我正在尝试转换
data_table = {"Red":[1,2,3], "Blue":[4,5,6]}
到
data_table = [ {"Red": 1, "Blue": 4 }, {"Red": 2, "Blue": 5}, {"Red": 3, "Blue": 6}]
一种可能的方法是使用 pandas 数据框。在某些情况下,我们的字典中有超过 100 个键。
import pandas as pd
df = pd.DataFrame(data_table, index=['row1', 'row2', 'row3'])
print(df.to_dict('records'))
我真正想知道data_table 中的键是否具有不相等的值。在以下示例中,“Black”在列表中有 2 个值,而字典中的所有其他键都有 3 个与之关联的值。
data_new = {'Red': [1,2,3], 'Blue': [4,5,6], 'Green': [7,8,9], 'Black': [0,10]}
到
data_new = [{'Red': 1, 'Blue':4,'Green':7, 'Black':0}, {'Red': 2, 'Blue':5,'Green': 8,'Black': 10}, {'Red': 3, 'Blue': 6, 'Green':9}]
Pandas dataFrame 方法因无法广播而失败。
任何可能的方法都会有所帮助。
【问题讨论】:
标签: python python-3.x pandas dataframe dictionary