小编Raf*_*afG的帖子

在Pandas DataFrame中查找所有最大索引

我需要找到所有索引,其中在Pandas DataFrame中获得最大值(每行).例如,如果我有这样的dataFrame:

   cat1  cat2  cat3
0     0     2     2
1     3     0     1
2     1     1     0
Run Code Online (Sandbox Code Playgroud)

那么我正在寻找的方法会产生如下结果:

[['cat2', 'cat3'],
 ['cat1'],
 ['cat1', 'cat2']]
Run Code Online (Sandbox Code Playgroud)

这是一个列表列表,但其他一些数据结构也没问题.

我不能使用df.idxmax(axis=1),因为它只产生第一个最大值.

python pandas

6
推荐指数
1
解决办法
2484
查看次数

与dict.fromkeys()和类似dict的对象的KeyError

在Python中,您可以使用字典作为第一个参数dict.fromkeys(),例如:

In [1]: d = {'a': 1, 'b': 2}

In [2]: dict.fromkeys(d)
Out[2]: {'a': None, 'b': None}
Run Code Online (Sandbox Code Playgroud)

我尝试用类似dict的对象做同样的事情,但总是引发一个KeyError,例如:

In [1]: class SemiDict:
   ...:     def __init__(self):
   ...:         self.d = {}
   ...:
   ...:     def __getitem__(self, key):
   ...:         return self.d[key]
   ...:
   ...:     def __setitem__(self, key, value):
   ...:         self.d[key] = value
   ...:
   ...:

In [2]: sd = SemiDict()

In [3]: sd['a'] = 1

In [4]: dict.fromkeys(sd)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)

C:\bin\Console2\<ipython console> in <module>()

C:\bin\Console2\<ipython console> in …
Run Code Online (Sandbox Code Playgroud)

python dictionary

3
推荐指数
1
解决办法
1368
查看次数

标签 统计

python ×2

dictionary ×1

pandas ×1