【问题标题】:How to find the values of a column in a dataframe that doesn't satisfy a condition? [closed]如何在不满足条件的数据框中查找列的值? [关闭]
【发布时间】:2021-05-02 19:15:35
【问题描述】:

像这样考虑我的示例数据框“df”:

S.no Phone
1 955290232
2 8752837492
3 9342832245
4 919485928837
5 917482482938
6 98273642733

我的结果表必须具有不满足 2 个条件的值:

  1. 没有“91”前缀的值。
  2. 每个值的长度是 >12 或

我的结果表:

|S.no   |  Phone      |
--------|--------------
|1      |955290232    |
|2      |8752837492   |
|3      |9342832245   |
|6      |98273642733  |

这是怎么做到的?

【问题讨论】:

  • 你试过什么?看起来像 .str.startswith('91').str.len() 的简单过滤
  • 这是简单的布尔否定。您的编码尝试和遇到的问题在哪里?

标签: python pandas dataframe numpy


【解决方案1】:

使用str.startswithstr.len 创建过滤器:

import pandas as pd

df = pd.DataFrame({'S.no': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6},
                   'Phone': {0: 955290232, 1: 8752837492, 2: 9342832245,
                             3: 919485928837, 4: 917482482938, 5: 98273642733}})

# Get Phone as STR for STR Methods
s = df['Phone'].astype(str)

# Build Filter
m = ((~s.str.startswith("91")) &
     (s.str.len() != 12))

# Filtered DataFrame
filtered_df = df[m]

# For Display
print(filtered_df.to_string(index=False))

输出:

S.no       Phone
   1   955290232
   2  8752837492
   3  9342832245
   6 98273642733

【讨论】:

    猜你喜欢
    • 2016-03-17
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多