python - 从 pandas where() 中排除列

标签 python python-2.7 pandas

我有以下 pandas df :

import pandas as pd
import numpy as np    

pd_df = pd.DataFrame({'Qu1': ['apple', 'potato', 'cheese', 'banana', 'cheese', 'banana', 'cheese', 'potato', 'egg'],
              'Qu2': ['sausage', 'banana', 'apple', 'apple', 'apple', np.nan, 'banana', 'banana', 'banana'],
              'Qu3': ['apple', 'potato', 'sausage', 'cheese', 'cheese', 'potato', 'cheese', 'potato', 'egg']})

我想仅在 Qu1Qu2 两列上实现 where() 并保留其余部分 original stackoverflow question ,所以我创建了 pd1

pd1 = pd_df.where(pd_df.apply(lambda x: x.map(x.value_counts()))>=2,
                              "other")[['Qu1', 'Qu2']]

然后我将其余的 pd_dfpd_df['Qu3'] 添加到 pd1

pd1['Qu3'] = pd_df['Qu3']
pd_df = []

我的问题是:最初我想在 df 的一部分上执行 where() 并保持其余列不变,所以可以上面的代码对于大型数据集有危险吗?我这样会损坏原始数据吗?如果是,最好的方法是什么?

非常感谢!

最佳答案

您可以明确地获取原始 df 的副本,然后覆盖该 df 的选择:

In [40]:
pd1 = pd_df.copy()
pd1[['Qu1', 'Qu2']] = pd1[['Qu1', 'Qu2']].where(pd_df.apply(lambda x: x.map(x.value_counts()))>=2,
                              "other")
pd1

Out[40]:
      Qu1     Qu2      Qu3
0   other   other    apple
1  potato  banana   potato
2  cheese   apple  sausage
3  banana   apple   cheese
4  cheese   apple   cheese
5  banana   other   potato
6  cheese  banana   cheese
7  potato  banana   potato
8   other  banana      egg

所以这里的区别在于我们只对 df 的一部分进行操作,而不是对整个 df 进行操作,然后选择感兴趣的列

更新

如果您只想覆盖这些列,则只需选择它们:

In [48]:
pd_df[['Qu1', 'Qu2']] = pd_df[['Qu1', 'Qu2']].where(pd_df.apply(lambda x: x.map(x.value_counts()))>=2,
                              "other")
pd_df

Out[48]:
      Qu1     Qu2      Qu3
0   other   other    apple
1  potato  banana   potato
2  cheese   apple  sausage
3  banana   apple   cheese
4  cheese   apple   cheese
5  banana   other   potato
6  cheese  banana   cheese
7  potato  banana   potato
8   other  banana      egg

关于python - 从 pandas where() 中排除列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37317804/

相关文章:

使用 Fortran 的 Python 模块 : LNK1112 `module machine type ' X8 6' conflicts with target machine type ' x6 4'`

python - pandas 日期时间转unixtime

python - 遍历行以查看哪个值先出现

python - 描述符 : Precendence of Attribute access through __getattribute()__

python - 在 python 函数中使用列表

python - AWS Elastic Beanstalk 公开的源代码

python - 在 python 中将子列表更改为元组

python - 将 pd.DataFrame Styler 对象的背景渐变色图居中

python - 在 python matplotlib 中绘制公差线

python - 在python中将unicode转换为两个单独的列表