【问题标题】:Interact through df columns and filter then with a like string statement通过 df 列进行交互,然后使用类似的字符串语句进行过滤
【发布时间】:2022-06-13 22:05:17
【问题描述】:

想象一个具有多列的数据集,以 carr 开头

carr carrer banana
One Two Three

如何过滤这些列名,只返回以字符串“carr”开头的那些。

想要的结果

carr carrer
One Two

样本df:

import pandas as pd
pd.DataFrame({
    "Carrer":[1,2,3],
    "Carr":[2,3,1],
    "Banana":[1,5,7]
})

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用DataFrame.filter

    out = df.filter(regex='(?i)^carr')
    
    print(out)
    
       Carrer  Carr
    0       1     2
    1       2     3
    2       3     1
    

    【讨论】:

    • 你能不能让正则表达式不区分大小写。所以正则表达式接受大写和小写?请
    • @INGl0R1AM0R1 使用内联标记编辑。
    【解决方案2】:
    cols = df.columns
    sub = list(filter(lambda x: x.startswith('carr'), cols))
    df[sub]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多