팬더 : 이름이 X로 시작하는 모든 열을 선택하는 가장 좋은 방법
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],})
로 시작하는 열에서 1의 값을 선택하고 싶습니다 foo.
. 다음보다 더 좋은 방법이 있습니까?
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]
목록 이해를 수행하여 열을 만듭니다.
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
이제 pandas의 인덱스가 문자열 연산을 지원하므로 'foo'로 시작하는 열을 선택하는 가장 간단하고 가장 좋은 방법은 다음과 같습니다.
df.loc[:, df.columns.str.startswith('foo')]
Alternatively, you can filter column (or row) labels with df.filter()
. To specify a regular expression to match the names beginning with 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
To select only the required rows (containing a 1
) and the columns, you can use loc
, selecting the columns using filter
(or any other method) and the rows using 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
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
Another option for the selection of the desired entries is to use map
:
df.loc[(df == 1).any(axis=1), df.columns.map(lambda x: x.startswith('foo'))]
which gives you all the columns for rows that contain a 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
The row selection is done by
(df == 1).any(axis=1)
as in @ajcr's answer which gives you:
0 True
1 True
2 True
3 False
4 False
5 True
dtype: bool
meaning that row 3
and 4
do not contain a 1
and won't be selected.
The selection of the columns is done using Boolean indexing like this:
df.columns.map(lambda x: x.startswith('foo'))
In the example above this returns
array([False, True, True, True, True, True, False], dtype=bool)
So, if a column does not start with foo
, False
is returned and the column is therefore not selected.
If you just want to return all rows that contain a 1
- as your desired output suggests - you can simply do
df.loc[(df == 1).any(axis=1)]
which returns
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
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()
.
'developer tip' 카테고리의 다른 글
가져 오지 않은 지연 객체에 대한 Jackson 직렬화 방지 (0) | 2020.10.29 |
---|---|
Swift에서 매개 변수로 이미지 업로드 (0) | 2020.10.29 |
KDiff3 :“선 끝 스타일 충돌이 있습니다.” (0) | 2020.10.29 |
다 대다 필드를위한 Django ModelForm (0) | 2020.10.29 |
앱이 내 뷰의 백그라운드로 들어갈 때를 감지하는 가장 좋은 방법은 무엇입니까? (0) | 2020.10.28 |