Pandas 来自 Dict 键和值列表的数据框对多行具有相同的键
Pandas Dataframe from Dict key and list of values to have same key for multiple rows
我通过以下方式创建了字典:
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'
我想让字典键位于与其关联的列表中的每个项目的每一行中。我试过制作两个系列并将它们连接起来,但没有成功。我一定是想多了。提前感谢您的任何见解。
所以 BrenBarn 让我走上了正确的道路,所以我做了以下事情:
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
我通过以下方式创建了字典:
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'
我想让字典键位于与其关联的列表中的每个项目的每一行中。我试过制作两个系列并将它们连接起来,但没有成功。我一定是想多了。提前感谢您的任何见解。
所以 BrenBarn 让我走上了正确的道路,所以我做了以下事情:
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