Python 将Dict键和值列表中的数据帧转换为多行具有相同键

Python 将Dict键和值列表中的数据帧转换为多行具有相同键,python,dictionary,pandas,Python,Dictionary,Pandas,我通过以下方式创建了一本词典: test_df = {} for row in df.iterrows(): y = [] for x in row[1]: y.append(x) test_df[y[0]] = y[1:] 我的口述是这样的: {'City': ['Item1', 'Item2', 'Item3', 'Item4', 'Item5']} A B 'City' 'Item1' 'City' 'Item2'

我通过以下方式创建了一本词典:

test_df = {}
for row in df.iterrows():
    y = []
    for x in row[1]:
        y.append(x)
    test_df[y[0]] = y[1:]
我的口述是这样的:

{'City': ['Item1',
  'Item2',
  'Item3',
  'Item4',
  'Item5']}
A       B
'City'  'Item1'
'City'  'Item2'
'City'  'Item3'
'City'  'Item4'
'City'  'Item5'
我似乎无法获得如下所示的数据帧:

{'City': ['Item1',
  'Item2',
  'Item3',
  'Item4',
  'Item5']}
A       B
'City'  'Item1'
'City'  'Item2'
'City'  'Item3'
'City'  'Item4'
'City'  'Item5'
我希望字典键位于列表中与其关联的每一项的每一行中。我试着制作了两个系列,并对它们进行了处理,但没有成功。我一定是想太多了。提前感谢您提供的任何见解

布伦巴恩让我走上了正确的道路,所以我做了以下几件事:

x = [item[0] for item in test_df.items()]
df1 = pd.DataFrame({'A': x[0], 'B': test_df[x[0]]})
for row in x[1:]:
    df2 = pd.DataFrame({'A': row, 'B': test_df[row]})
    df1 = pd.concat([df1, df2])

它工作得很好。谢谢大家。

这里有一个简单的方法:

>>> pandas.DataFrame({"A": 'City', "B": d['City']})
      A      B
0  City  Item1
1  City  Item2
2  City  Item3
3  City  Item4
4  City  Item5

您是否特别需要支持dict格式?如果你是自己写的话,你为什么不创建一个与你想要的数据框结构更紧密匹配的结构呢?我的原始csv文件是这样的行:列a:“城市”列B:“项目1”列C:“项目2”列D:“项目3”列E:“项目4”列F:“项目5”如何更容易创建该数据框?请发布一个原始csv文件的示例csv。它有多行吗?每行上有相同数量的项吗?我尝试执行pd.DataFrame({'A':[x代表x在new_df.items()[0],'B':new_df.items()})但这给了我一个错误,数组的长度必须相同。如果字典中的每个键都是不同的城市,我如何定义它?@nahata5:请编辑您的问题,以显示您想要做的实际示例。