pandas:选择名称以X开头的所有列的最佳方法

ccs*_*csv 77 python selection dataframe pandas

我有一个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': [0, 1, np.nan, 0, 0, 0],
                   'foo.bars': [0, 0, 0, 0, 0, 1],
                   'bar.baz': [5, 5, 6, 5, 5.6, 6.8],
                   'foo.fox': [2, 4, 1, 0, 0, 5],
                   'nas.foo': ['NA', 0, 1, 0, 0, 0],
                   'foo.manchu': ['NA', 0, 0, 0, 0, 0],})
Run Code Online (Sandbox Code Playgroud)

我想在以foo..开头的列中选择值1 .有没有比这更好的方法:

df2 = df[(df['foo.aa'] == 1)|
(df['foo.fighters'] == 1)|
(df['foo.bars'] == 1)|
(df['foo.fox'] == 1)|
(df['foo.manchu'] == 1)
]
Run Code Online (Sandbox Code Playgroud)

类似于写东西的东西:

df2= df[df.STARTS_WITH_FOO == 1]
Run Code Online (Sandbox Code Playgroud)

答案应该打印出这样的DataFrame:

   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

[4 rows x 7 columns]
Run Code Online (Sandbox Code Playgroud)

EdC*_*ica 112

只需执行列表理解即可创建列:

In [28]:

filter_col = [col for col in df if col.startswith('foo')]
filter_col
Out[28]:
['foo.aa', 'foo.bars', 'foo.fighters', 'foo.fox', 'foo.manchu']
In [29]:

df[filter_col]
Out[29]:
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
3     4.7         0             0        0          0
4     5.6         0             0        0          0
5     6.8         1             0        5          0
Run Code Online (Sandbox Code Playgroud)

另一种方法是从列创建一个系列并使用vectorised str方法startswith:

In [33]:

df[df.columns[pd.Series(df.columns).str.startswith('foo')]]
Out[33]:
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
3     4.7         0             0        0          0
4     5.6         0             0        0          0
5     6.8         1             0        5          0
Run Code Online (Sandbox Code Playgroud)

为了实现您的目标,您需要添加以下内容来过滤不符合==1条件的值:

In [36]:

df[df[df.columns[pd.Series(df.columns).str.startswith('foo')]]==1]
Out[36]:
   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      NaN       1       NaN           NaN      NaN        NaN     NaN
1      NaN     NaN       NaN             1      NaN        NaN     NaN
2      NaN     NaN       NaN           NaN        1        NaN     NaN
3      NaN     NaN       NaN           NaN      NaN        NaN     NaN
4      NaN     NaN       NaN           NaN      NaN        NaN     NaN
5      NaN     NaN         1           NaN      NaN        NaN     NaN
Run Code Online (Sandbox Code Playgroud)

编辑

看到你想要的东西之后好的回答是这样的:

In [72]:

df.loc[df[df[df.columns[pd.Series(df.columns).str.startswith('foo')]] == 1].dropna(how='all', axis=0).index]
Out[72]:
   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
Run Code Online (Sandbox Code Playgroud)


Ale*_*ley 48

现在pandas的索引支持字符串操作,可以说选择以'foo'开头的列的最简单和最好的方法就是:

df.loc[:, df.columns.str.startswith('foo')]
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用过滤列(或行)标签df.filter().要指定正则表达式以匹配以下开头的名称foo.:

>>> df.filter(regex=r'^foo\.', axis=1)
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
3     4.7         0             0        0          0
4     5.6         0             0        0          0
5     6.8         1             0        5          0
Run Code Online (Sandbox Code Playgroud)

要仅选择所需的行(包含a 1)和列,您可以使用loc,使用filter(或任何其他方法)选择列,并使用以下行any:

>>> df.loc[(df == 1).any(axis=1), df.filter(regex=r'^foo\.', axis=1).columns]
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
5     6.8         1             0        5          0
Run Code Online (Sandbox Code Playgroud)


Moh*_*ieg 11

最简单的方法是直接在列名上使用str,不需要 pd.Series

df.loc[:,df.columns.str.startswith("foo")]


Run Code Online (Sandbox Code Playgroud)


小智 9

就我而言,我需要一个前缀列表

colsToScale=["production", "test", "development"]
dc[dc.columns[dc.columns.str.startswith(tuple(colsToScale))]]
Run Code Online (Sandbox Code Playgroud)


Myk*_*tko 8

filter您可以使用带有参数的方法like

df.filter(like='foo')
Run Code Online (Sandbox Code Playgroud)


Ric*_*cky 6

您可以尝试使用正则表达式来过滤掉以“foo”开头的列

df.filter(regex='^foo*')

如果您需要在列中包含字符串 foo 那么

df.filter(regex='foo*')

会是合适的。

对于下一步,您可以使用

df[df.filter(regex='^foo*').values==1]

过滤掉 'foo*' 列的值之一为 1 的行。