python - 用所有缺失的数据组合填充 list/pandas.dataframe(如 R 中的 complete())

标签 python pandas dictionary combinations

我有如下数据集(这是一个例子,它实际上有 66k 行):

        Type       Food      Loc  Num
0      Fruit     Banana  House-1   15
1      Fruit     Banana  House-2    4
2      Fruit      Apple  House-2    6
3      Fruit      Apple  House-3    8
4  Vegetable   Broccoli  House-3    8
5  Vegetable    Lettuce  House-4   12
6  Vegetable    Peppers  House-5    3
7  Vegetable       Corn  House-4    4
8  Seasoning  Olive Oil  House-6    2
9  Seasoning    Vinegar  House-7    2

我想用 0 填充所有缺失的组合(House 3-7 中有多少香蕉?除 House-5 之外还有多少辣椒?),得到如下内容:

        Type       Food      Loc  Num
0      Fruit     Banana  House-1   15
1      Fruit     Banana  House-2    4
2      Fruit     Banana  House-3    0
... fill remaining houses with zeros
6      Fruit     Banana  House-7    0
7      Fruit      Apple  House-1    0
8      Fruit      Apple  House-2    6
9      Fruit      Apple  House-3    8
... fill remaining houses with zeros
14  Vegetable   Broccoli  House-1    0
15  Vegetable   Broccoli  House-2    0
16  Vegetable   Broccoli  House-3    8
... etc    
n   Seasoning    Vinegar  House-7    2

我知道 R 有 complete function集成。

现在我一直在处理从原始 DataFrame 中提取的列表,我将其转换为字典。

for key,grp in fruit.groupby(level=0):
        dir[key] = test.ix[key].values.tolist()

fruit = {'Banana': [[1.0,15.0], [2.0,4.0],
         'Apple': [[2.0,6.0], [3.0,8.0]

#Type = {fruit1:[[Loc1,Count1],...,[Locn],[Countn],
#... fruitn:[...]}

我设计这个函数是为了应用于字典的赋值规则:

def fill_zeros(list):
    final = [0] * 127
    for i in list:
        final[int(i[0])] = i[1]
    return final

这适用于单个“水果”:

print fill_zeros(test.ix['QLLSEEEKK'].values.tolist())
print fill_zeros(test.ix['GAVPLEMLEIALR'].values.tolist())
print fill_zeros(test.ix['VPVNLLNSPDCDVK'].values.tolist())

但字典上没有:

for key,grp in test.groupby(level=0):
        dir[key] = fill_zeros(test.ix[key].values.tolist())

Traceback (most recent call last):
  File "peptidecount.py", line 59, in <module>
    print fill_zeros(test.ix[str(key)].values.tolist())
  File "peptidecount.py", line 43, in fill_zeros
    final[int(i[0])] = i[1]
TypeError: 'float' object has no attribute '__getitem__'

显然我没有正确地迭代字典。有办法纠正吗?还是有更合适的函数直接应用在DataFrame上?

最佳答案

你可以使用 reindex .

首先,您需要一个有效的 (type, food) 对列表。我将从数据本身获取它,而不是将它们写出来。

In [88]: kinds = list(df[['Type', 'Food']].drop_duplicates().itertuples(index=False))

In [89]: kinds
Out[89]:
[('Fruit', 'Banana'),
 ('Fruit', 'Apple'),
 ('Vegetable', 'Broccoli'),
 ('Vegetable', 'Lettuce'),
 ('Vegetable', 'Peppers'),
 ('Vegetable', 'Corn'),
 ('Seasoning', 'Olive Oil'),
 ('Seasoning', 'Vinegar')]

现在我们将使用 itertools.product 为那些 kinds 的房子生成所有对。

In [93]: from itertools import product

In [94]: houses = ['House-%s' % x for x in range(1, 8)]

In [95]: idx = [(x.Type, x.Food, house) for x, house in product(kinds, houses)]

In [96]: idx[:2]
Out[96]: [('Fruit', 'Banana', 'House-1'), ('Fruit', 'Banana', 'House-2')]

现在您可以使用 set_indexreindex 来获取缺失的观察值。

In [98]: df.set_index(['Type', 'Food', 'Loc']).reindex(idx, fill_value=0)
Out[98]:
                           Num
Type      Food    Loc
Fruit     Banana  House-1   15
                  House-2    4
                  House-3    0
                  House-4    0
                  House-5    0
...                        ...
Seasoning Vinegar House-3    0
                  House-4    0
                  House-5    0
                  House-6    0
                  House-7    2

[56 rows x 1 columns]

关于python - 用所有缺失的数据组合填充 list/pandas.dataframe(如 R 中的 complete()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37998861/

相关文章:

python - 集成 Qt Designer 和 PyCharm

python - 如何在 Python 中正确检查对象类型?

python - Pandas reshape 柱形

python - 仅在创建 MultiIndex 时 Pandas DatetimeIndex NonExistentTimeError

python - 从包含名称+日期的字符串中提取日期

c# - 在不遇到集合修改异常的情况下从列表中删除项目的最有效方法?

c# - 如何保持字典有序?

python - python中字典的过滤列表

Python 多处理池没有创建足够的进程

python元组到dict