如何在 pandas DataFrame 中选择名称以 X 开头的所有列

问题描述 投票:0回答:12

我有一个数据框:

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],})

我想在以

foo.
开头的列中选择 1 的值。除了:

之外还有更好的方法吗?
df2 = df[(df['foo.aa'] == 1)|
(df['foo.fighters'] == 1)|
(df['foo.bars'] == 1)|
(df['foo.fox'] == 1)|
(df['foo.manchu'] == 1)
]

类似于写这样的东西:

df2= df[df.STARTS_WITH_FOO == 1]

答案应该打印出这样的 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]
python pandas dataframe selection
12个回答
250
投票

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

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

另一种方法是从列创建一系列并使用矢量化 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

为了实现您想要的目标,您需要添加以下内容来过滤不符合您的

==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

编辑

好的,在看到你想要的内容后,复杂的答案是这样的:

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

106
投票

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

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

或者,您可以使用

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

要仅选择所需的行(包含

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

17
投票

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

pd.Series

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



8
投票

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

colsToScale=["production", "test", "development"]
dc[dc.columns[dc.columns.str.startswith(tuple(colsToScale))]]

8
投票

您可以使用方法

filter
和参数
like

df.filter(like='foo')

5
投票

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

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

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

df.filter(regex='foo*')

比较合适。

对于下一步,您可以使用

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

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


3
投票

根据@EdChum的回答,您可以尝试以下解决方案:

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

如果您想要选择的列并非全部以

foo
开头,这将非常有用。此方法选择包含子字符串
foo
的所有列,并且可以将其放置在列名称的任意位置。

本质上,我用

.startswith()
替换了
.contains()


2
投票

选择所需条目的另一个选项是使用

map
:

df.loc[(df == 1).any(axis=1), df.columns.map(lambda x: x.startswith('foo'))]

它为您提供包含

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
5     6.8         1             0        5          0

行选择

完成
(df == 1).any(axis=1)

就像 @ajcr 的回答一样:

0     True
1     True
2     True
3    False
4    False
5     True
dtype: bool

意味着行

3
4
不包含
1
并且不会被选择。

列的选择是使用布尔索引完成的,如下所示:

df.columns.map(lambda x: x.startswith('foo'))

在上面的例子中返回

array([False,  True,  True,  True,  True,  True, False], dtype=bool)

因此,如果列不是以

foo
开头,则会返回
False
,因此不会选择该列。

如果您只想返回包含

1
的所有行 - 正如您所需的输出所示 - 您只需这样做

df.loc[(df == 1).any(axis=1)]

返回

   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

1
投票

我不喜欢其他解决方案要求我们两次引用 DataFrame;如果您只有一个名为

df
的框架可能没问题,但情况通常并非如此(并且您的实际名称可能会更长)。让我们利用 pandas 索引功能来减少输入,并使代码更具可读性。没有什么可以阻止我们使用这样的东西:

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

因为索引器可以是任何

Callable
。然后我们甚至可以将此伪索引器分配给一个变量并将其用于多个帧:

foo_columns = columns.startswith('foo')
df_1.loc[:, foo_columns]
df_2.loc[:, foo_columns]

我们甚至可以将其打印精美:

> foo_columns
<function __main__.PandasIndexer:columns.str.startswith(pat='foo')()>

我们可以使用

str
访问器的任何其他方法,例如
columns.contains(r'bar\d', regex=True)
,同时获得有用的签名:

> columns.contains
<function __main__.PandasIndexer:columns.str.contains(pat, case=True, flags=0, na=None, regex=True)>

全部用这个简短的魔法代码:

from pandas import Series
from inspect import signature, Signature


class PandasIndexer:
    def __init__(self, axis_name, accessor='str'):
        """
        Args:
            - axis_name: `columns` or `index`
            - accessor: e.g. `str`, or `dt`
        """
        self._axis_name = axis_name
        self._accessor = accessor
        self._dummy_series = Series(dtype=object)

    def _create_indexer(self, attribute):
        dummy_accessor = getattr(self._dummy_series, self._accessor)
        dummy_attr = getattr(dummy_accessor, attribute)
        name = f'PandasIndexer:{self._axis_name}.{self._accessor}.{attribute}'

        def indexer_factory(*args, **kwargs):
            def indexer(df):
                axis = getattr(df, self._axis_name)
                accessor = getattr(axis, self._accessor)
                method = getattr(accessor, attribute)
                return method(*args, **kwargs)

            bound_arguments = signature(dummy_attr).bind(*args, **kwargs)
            indexer.__qualname__ = (
                name + str(bound_arguments).replace('<BoundArguments ', '')[:-1]
            )
            indexer.__signature__ = Signature()
            return indexer

        indexer_factory.__name__ = name
        indexer_factory.__qualname__ = name
        indexer_factory.__signature__ = signature(dummy_attr)
        return indexer_factory

    def __getattr__(self, attribute):
        return self._create_indexer(attribute)

    def __dir__(self):
        """Make it work with auto-complete in IPython"""
        return dir(getattr(self._dummy_series, self._accessor))


columns = PandasIndexer('columns')

1
投票

即使您可以尝试使用多个前缀:

temp = df.loc[:, df.columns.str.startswith(('prefix1','prefix2','prefix3'))]

0
投票

我的解决方案。性能可能会较慢:

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

0
投票

一个选项是使用 pyjanitor 的 select 函数:

# pip install pyjanitor
import janitor 
import pandas as pd

df.select(columns='foo*')
Out[32]: 
   foo.aa  foo.fighters  foo.bars  foo.fox foo.manchu
0     1.0           0.0         0        2         NA
1     2.1           1.0         0        4          0
2     NaN           NaN         0        1          0
3     4.7           0.0         0        0          0
4     5.6           0.0         0        0          0
5     6.8           0.0         1        5          0
© www.soinside.com 2019 - 2024. All rights reserved.