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

前端 未结 8 1189
别那么骄傲
别那么骄傲 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:31

    My solution. It may be slower on performance:

    a = pd.concat(df[df[c] == 1] for c in df.columns if c.startswith('foo'))
    a.sort_index()
    
    
       bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
    0      5.0     1.0         0             0        2         NA      NA
    1      5.0     2.1         0             1        4          0       0
    2      6.0     NaN         0           NaN        1          0       1
    5      6.8     6.8         1             0        5          0       0
    

提交回复
热议问题