【问题标题】:Python.pandas: how to select rows where objects start with letters 'PL'Python.pandas:如何选择对象以字母“PL”开头的行
【发布时间】:2020-06-15 21:15:05
【问题描述】:

我对 pandas 有特定的问题:我需要在数据框中选择以特定字母开头的行。 详细信息:我已将数据导入数据框并选择了我需要的列。我还将它缩小到我需要的行索引。现在我还需要在其他列中选择对象以字母“pl”开头的行。

是否有任何解决方案可以仅根据其中的前两个字符选择行?

我在想

pl = df[‘Code’] == pl*

但由于行索引,它不会工作。建议赞赏!

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

为此使用startswith

df = df[df['Code'].str.startswith('pl')]

【讨论】:

    【解决方案2】:

    对于那些想尝试它的人来说,完全可复制的例子。

    import pandas as pd
    
    df = pd.DataFrame([["plusieurs", 1], ["toi", 2], ["plutot", 3]])
    
    df.columns = ["Code", "number"]
    
    df = df[df.Code.str.startswith("pl")] # alternative is df = df[df["Code"].str.startswith("pl")]
    

    【讨论】:

      【解决方案3】:

      如果您在 Series 上使用字符串方法,应该会返回真/假结果。然后,您可以将其用作与 .loc 结合的过滤器来创建您的数据子集。

      new_df = df.loc[df[‘Code’].str.startswith('pl')].copy()
      

      【讨论】:

        【解决方案4】:

        条件只是一个过滤器,然后您需要将其应用于数据框。作为过滤器,您可以使用Series.str.startswith 方法并执行

        df_pl = df[df['Code'].str.startswith('pl')]
        

        【讨论】:

        • 这与其他答案相同。
        猜你喜欢
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-24
        • 2022-07-13
        • 1970-01-01
        相关资源
        最近更新 更多