pandas: best way to select all columns whose names start with X

前端 未结 8 1193
别那么骄傲
别那么骄傲 2020-11-27 10:03

I have a DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame({\'foo.aa\': [1, 2.1, np.nan, 4.7, 5.6, 6.8],
                   \'foo.fighters         


        
8条回答
  •  旧巷少年郎
    2020-11-27 10:36

    Based on @EdChum's answer, you can try the following solution:

    df[df.columns[pd.Series(df.columns).str.contains("foo")]]
    

    This will be really helpful in case not all the columns you want to select start with foo. This method selects all the columns that contain the substring foo and it could be placed in at any point of a column's name.

    In essence, I replaced .startswith() with .contains().

提交回复
热议问题