首页 \ 问答 \ Pandas:用唯一值替换多个列值(Pandas: Replace multiple column values by unique value)

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
更新时间:2022-05-19 19:05

最满意答案

它们是相同的,但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)

相关问答

更多
  • 可能不会。 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])
  • 你可以捕获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 ...
  • 使用生成器表达式: 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 ...
  • 您正在调用存在的方法,但方法声明中没有参数。 那个方法是 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中的所有内容都通过引用传递。 因此,在上面的情况下, 生成器 q是对函数的原始deque持有的引用,因此任何可以修改deque的方法都会破坏生成的原始算法。 当你用iter()包围q ,你实际产生的是迭代器。 您可以从迭代器(读取)中获取元素,但不能自行更改元素或修改它们的顺序(不允许写入)。 因此,保护内部容器保持免受意外损坏是一种很好的做法。 To answer second part of the question, everything in Python is p ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)