【问题标题】:Select rows from a DataFrame based on string values in a column in pandas根据熊猫列中的字符串值从DataFrame中选择行
【发布时间】:2018-04-04 10:12:05
【问题描述】:

如何根据 pandas 列中的字符串值从 DataFrame 中选择行?我只想显示所有大写字母中的唯一状态。 各州有城市总数。

import pandas as pd
import matplotlib.pyplot as plt
%pylab inline
d = pd.read_csv("states.csv")
print(d)
print(df)
# States/cities           B  C   D
# 0  FL                   3  5   6
# 1  Orlando              1  2   3
# 2  Miami                1  1   3
# 3  Jacksonville         1  2   0
# 4  CA                   8  3   2
# 5  San diego            3  1   0
# 6  San Francisco        5  2   2
# 7  WA                   4  2   1
# 8  Seattle              3  1   0 
# 9  Tacoma               1  1   1

如何显示,

# States/Cites        B   C   D
# 0  FL               3  5   6               
# 4  CA               8  3   2
# 7  WA               4  2   1

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以编写一个函数以应用于States/cities 列中的每个值。让函数返回 True 或 False,应用函数的结果可以作为 DataFrame 上的布尔过滤器。

    这是使用 pandas 时的常见模式。在您的特定情况下,您可以检查 States/cities 中的每个值是否仅由大写字母组成。

    例如:

    def is_state_abbrev(string):
        return string.isupper()
    
    filter = d['States/cities'].apply(is_state_abbrev)
    filtered_df = d[filter]
    

    这里的filter 将是一个带有TrueFalse 值的熊猫系列。

    您也可以使用 lambda 表达式来获得相同的结果,如下所示:

    filtered_df = d[d['States/cities'].apply(lambda x: x.isupper())]
    

    这基本上做同样的事情。

    【讨论】:

      【解决方案2】:

      考虑 pandas.Series.str.match 只为 [A-Z] 传递正则表达式

      states[states['States/cities'].str.match('^.*[A-Z]$')]
      
      #   States/cities  B  C  D
      # 0            FL  3  5  6
      # 4            CA  8  3  2
      # 7            WA  4  2  1
      

      数据

      from io import StringIO
      import pandas as pd
      
      txt = '''"States/cities"           B  C   D
      0  FL                   3  5   6
      1  Orlando              1  2   3
      2  Miami                1  1   3
      3  Jacksonville         1  2   0
      4  CA                   8  3   2
      5  "San diego"            3  1   0
      6  "San Francisco"        5  2   2
      7  WA                   4  2   1
      8  Seattle              3  1   0 
      9  Tacoma               1  1   1'''
      
      states = pd.read_table(StringIO(txt), sep="\s+")
      

      【讨论】:

        【解决方案3】:

        您可以像这样在States/cities 列中获取所有大写值的行:

        df.loc[df['States/cities'].str.isupper()]
        
          States/cities  B  C  D
        0            FL  3  5  6
        4            CA  8  3  2
        7            WA  4  2  1
        

        为了安全起见,您可以添加一个条件,使其仅返回 'States/cities' 为大写的行并且只有 2 个字符长(如果您的值为 SEATTLE或类似的东西):

        df.loc[(df['States/cities'].str.isupper()) & (df['States/cities'].apply(len) == 2)]
        

        【讨论】:

          【解决方案4】:

          您可以使用 str.contains 过滤任何包含小字母的行

          df[~df['States/cities'].str.contains('[a-z]')]
          
              States/cities   B   C   D
          0   FL              3   5   6
          4   CA              8   3   2
          7   WA              4   2   1
          

          【讨论】:

            【解决方案5】:

            如果我们假设顺序总是 State 之后是 state 中的城市,我们可以使用 wheredropna

            df['States/cities']=df['States/cities'].where(df['States/cities'].isin(['FL','CA','WA']))
            
            
            df.dropna()
            df
              States/cities  B  C  D
            0            FL  3  5  6
            4            CA  8  3  2
            7            WA  4  2  1
            

            或者我们做str.len

            df[df['States/cities'].str.len()==2]
            Out[39]: 
              States/cities  B  C  D
            0            FL  3  5  6
            4            CA  8  3  2
            7            WA  4  2  1
            

            【讨论】:

              猜你喜欢
              • 2016-07-24
              • 1970-01-01
              • 2018-08-05
              • 2015-10-23
              相关资源
              最近更新 更多