Pandas:用唯一值替换多个列值(Pandas: Replace multiple column values by unique value)
我有一个有许多“对象”列的熊猫数据框,其中每个列都包含许多值(模态)。 然后,我想只保留每列10个最常见的模式 ,其他人则用'Oth'替换。
例如,如果我有一个包含4个不同值的列'obj_col1':
obj_col1 'A' 'A' 'B' 'C' 'B' 'D'
我想保留2个最常用的,这里是'A'和'B',并用'Oth'代替其余部分:
obj_col2 'A' 'A' 'B' 'Oth' 'B' 'Oth'
一个对象列(分类变量)的代码是:
# sorted list of modalities of 'categ_var' list_freq_modal = df['categ_var'].value_counts().index.tolist() # replace all the modalities except the first 10 by 'Oth' df['categ_var'].replace(list_freq_modal[10:],'Oth', inplace=True)
但是我有一个错误:'NoneType'对象没有任何属性'any'
你有没有想法以更优化的方式实现它?
I have a pandas DataFrame with many "object" columns where each of them contains many values (modalities). Then, I want to keep only the 10 most frequent modalities for each column and the others replace by 'Oth'.
For example, if I have a column 'obj_col1' which contains 4 different values:
obj_col1 'A' 'A' 'B' 'C' 'B' 'D'
and I want to keep 2 the most frequent, here 'A' and 'B', and replace the rest by 'Oth':
obj_col2 'A' 'A' 'B' 'Oth' 'B' 'Oth'
A piece of code for one object column (categorical variable) is:
# sorted list of modalities of 'categ_var' list_freq_modal = df['categ_var'].value_counts().index.tolist() # replace all the modalities except the first 10 by 'Oth' df['categ_var'].replace(list_freq_modal[10:],'Oth', inplace=True)
But I have an error : 'NoneType' object has no attribute 'any'
Have you any idea have implement it in more optimal way ?
原文:https://stackoverflow.com/questions/47287191
最满意答案
它们是相同的,但PEP 8更喜欢第二个版本。 我不相信它总是更容易阅读,所以要用自己的判断。
http://www.python.org/dev/peps/pep-0008/#programming-recommendations
对于序列,(字符串,列表,元组),请使用空序列为假的事实。
Yes: if not seq: if seq: No: if len(seq) if not len(seq)
They're the same, but PEP 8 prefers the second version. I'm not convinced that it's always easier to read though, so use your own judgement.
http://www.python.org/dev/peps/pep-0008/#programming-recommendations
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq: if seq: No: if len(seq) if not len(seq)
相关问答
更多-
下列中不属于面向对象的编程语言的是?[2022-05-30]
a -
可能不会。 LinkedHashMap有一些工具来构建带有驱逐策略的缓存,但这可能对你想要的东西有点过分。 只需扩展Deque并添加自定义逻辑;-) 编辑: class MyFixedSizeDeque
extends ArrayDeque { private int maxSize; public MyDeque(int size) { this.maxSize = size; } @Override public void addLast( ... -
你可以试试这个: from collections import deque deq = deque([1, 2, 3, 4]) del deq[1] print(deq) 输出: deque([1, 3, 4]) You can try this : from collections import deque deq = deque([1, 2, 3, 4]) del deq[1] print(deq) Output: deque([1, 3, 4])
-
Python while while循环popleft() - 错误:空双端队列(Python while loop popleft() - ERROR: Empty deque)[2022-03-17]
你可以捕获IndexError: try: while mydeque: alpha = mydeque.popleft() beta = mydeque.popleft() gamma = mydeque.popleft() except IndexError: # handle empty mydeque 你想做什么? 为什么要检查mydeque是否为空? You can catch the IndexError: try: wh ... -
复制一个空的双端队列(Copy an empty deque)[2021-11-14]
使用生成器表达式: i, j, k, l = (collections.deque() for _ in xrange(4)) Use a generator expression: i, j, k, l = (collections.deque() for _ in xrange(4)) -
a和d引用同一个对象。 所以如果你clear它,它将被清除为“两个变量”。 你可以通过打印对象的身份来检查。 >>> id(a) 44988624L >>> id(d) 44988624L 通过赋值复制值可能对于像int等基本数据类型是可能的。如果处理对象,则必须复制该对象,因为变量本身只是持有对该对象的引用。 你可以这样做 d = deque('abc') a = deque('abc') 或与 >>> import copy >>> d = copy.copy(a) 这导致了 >>> id(a) ...
-
它们是相同的,但PEP 8更喜欢第二个版本。 我不相信它总是更容易阅读,所以要用自己的判断。 http://www.python.org/dev/peps/pep-0008/#programming-recommendations 对于序列,(字符串,列表,元组),请使用空序列为假的事实。 Yes: if not seq: if seq: No: if len(seq) if not len(seq) They're the same, but PEP 8 prefers the se ...
-
在java中的deque实现中我的类型的方法未定义(Method undefined for my type in a deque implementation in java)[2022-04-15]
您正在调用存在的方法,但方法声明中没有参数。 那个方法是 public T dequeueRear() 并尝试执行以下操作 cad.dequeueRear(22); 您必须执行以下操作 cad.dequeueRear(); You are calling a method that exists but there is no parameter in the method declaration. That method is public T dequeueRear() and you try ... -
TL; DR:假设你的deque被称为d ,只需检查d[-1] ,因为双端队列中的“最右边”元素是前面的(你可能想要在双端队列长度之前测试以确保它不是空的) 。 考虑@ asongtoruin的建议, if d:用来测试deque是否为空(它相当于if len(d) == 0: :,但更多pythonic) 为什么不转换成列表? 因为deque s是可索引的,你正在测试前端 。 虽然deque具有类似于列表的接口,但实现针对前端操作和后端操作进行了优化。 引用文档 : Deques支持线程安全,内存有效的附 ...
-
python deque了解(python deque understanding)[2023-08-03]
要回答问题的第二部分,Python中的所有内容都通过引用传递。 因此,在上面的情况下, 生成器 q是对函数的原始deque持有的引用,因此任何可以修改deque的方法都会破坏生成的原始算法。 当你用iter()包围q ,你实际产生的是迭代器。 您可以从迭代器(读取)中获取元素,但不能自行更改元素或修改它们的顺序(不允许写入)。 因此,保护内部容器保持免受意外损坏是一种很好的做法。 To answer second part of the question, everything in Python is p ...