Pandas: 迭代字典时逐行添加
Pandas: Adding row by row while iterating a dictionary
我有两个大词典,其中的列表有值。出于这个问题的目的,我将它们命名为字典 foo 和 bar。
foo = {}
foo['a'] = []
foo['b'] = []
foo['a'].append(1)
foo['a'].append(2)
foo['b'].append(10)
foo['b'].append(30)
bar = {}
bar['a'] = []
bar['a'].append(5)
bar['a'].append(7)
bar['b'] = []
bar['b'].append(8)
bar['b'].append(34)
bar['b'].append(32)
通过迭代一个字典,我想构建一个数据框,它将让我得到以下数据 table:
id | viewed | presented
-----------------------
a | [1,2] | [5,7]
-----------------------
b | [10,30]| [8,32,34]
所以我做了以下事情:
import pandas as pd
df = pd.DataFrame(columns=['id', 'viewed', 'presented'])
for item in foo:
df = pd.Series({'id':item, 'viewed':foo[item], 'presented':bar[item]})
但是当我打印数据框时,它缺少 foo[a]
和 bar[a]
的结果
>>> df
id b
presented [8, 34, 32]
viewed [10, 30]
dtype: object
>>> len(df.index)
3
看起来它被覆盖了而不是增加数据帧的索引来记录下一个元素。在这种情况下,解决此问题并根据需要按行插入的最佳方法是什么。我查看了另外两个 Whosebug 问题都没有解决方案。
您只需:
df = pd.DataFrame({'viewed':foo, 'presented':bar}).reset_index()
df.columns = ['id', 'viewed', 'presented']
您将获得所需的数据框:
id viewed presented
0 a [1, 2] [5, 7]
1 b [10, 30] [8, 34, 32]
我有两个大词典,其中的列表有值。出于这个问题的目的,我将它们命名为字典 foo 和 bar。
foo = {}
foo['a'] = []
foo['b'] = []
foo['a'].append(1)
foo['a'].append(2)
foo['b'].append(10)
foo['b'].append(30)
bar = {}
bar['a'] = []
bar['a'].append(5)
bar['a'].append(7)
bar['b'] = []
bar['b'].append(8)
bar['b'].append(34)
bar['b'].append(32)
通过迭代一个字典,我想构建一个数据框,它将让我得到以下数据 table:
id | viewed | presented
-----------------------
a | [1,2] | [5,7]
-----------------------
b | [10,30]| [8,32,34]
所以我做了以下事情:
import pandas as pd
df = pd.DataFrame(columns=['id', 'viewed', 'presented'])
for item in foo:
df = pd.Series({'id':item, 'viewed':foo[item], 'presented':bar[item]})
但是当我打印数据框时,它缺少 foo[a]
和 bar[a]
>>> df
id b
presented [8, 34, 32]
viewed [10, 30]
dtype: object
>>> len(df.index)
3
看起来它被覆盖了而不是增加数据帧的索引来记录下一个元素。在这种情况下,解决此问题并根据需要按行插入的最佳方法是什么。我查看了另外两个 Whosebug 问题都没有解决方案。
您只需:
df = pd.DataFrame({'viewed':foo, 'presented':bar}).reset_index()
df.columns = ['id', 'viewed', 'presented']
您将获得所需的数据框:
id viewed presented
0 a [1, 2] [5, 7]
1 b [10, 30] [8, 34, 32]