다중 인덱스 팬더에서 선택
저는 'A'와 'B' 열이 있는 다중 인덱스 데이터 프레임을 가지고 있습니다.
인덱스를 단일 열 인덱스로 재설정하지 않고 다중 인덱스의 한 열에서 필터링하여 행을 선택하는 방법이 있습니까?
예를들면.
# has multi-index (A,B)
df
#can I do this? I know this doesn't work because the index is multi-index so I need to specify a tuple
df.ix[df.A ==1]
한 가지 방법은 다음을 사용하는 것입니다.get_level_values
색인 방법:
In [11]: df
Out[11]:
0
A B
1 4 1
2 5 2
3 6 3
In [12]: df.iloc[df.index.get_level_values('A') == 1]
Out[12]:
0
A B
1 4 1
0.13에서는 인수와 함께 다음을 사용할 수 있습니다.
df.xs(1, level='A', drop_level=False) # axis=1 if columns
참고: 인덱스가 아닌 열 MultiIndex인 경우 다음과 같은 기술을 사용할 수 있습니다.
In [21]: df1 = df.T
In [22]: df1.iloc[:, df1.columns.get_level_values('A') == 1]
Out[22]:
A 1
B 4
0 1
제 생각에 아주 쉽게 읽을 수 있고 쉽게 사용할 수 있는 것을 사용할 수도 있습니다.
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [10, 20, 50, 80], 'C': [6, 7, 8, 9]})
df = df.set_index(['A', 'B'])
C
A B
1 10 6
2 20 7
3 50 8
4 80 9
이제 여러분이 생각하고 있던 것에 대해 간단히 다음을 수행할 수 있습니다.
df.query('A == 1')
C
A B
1 10 6
다음을 사용하여 보다 복잡한 쿼리를 수행할 수도 있습니다.and
df.query('A >= 1 and B >= 50')
C
A B
3 50 8
4 80 9
그리고.or
df.query('A == 1 or B >= 50')
C
A B
1 10 6
3 50 8
4 80 9
다른 인덱스 수준에 대해 쿼리할 수도 있습니다.
df.query('A == 1 or C >= 8')
돌아올 것입니다
C
A B
1 10 6
3 50 8
4 80 9
쿼리 내에 변수를 사용하려면 다음을 사용할 수 있습니다.
b_threshold = 20
c_threshold = 8
df.query('B >= @b_threshold and C <= @c_threshold')
C
A B
2 20 7
3 50 8
사용가능DataFrame.xs()
:
In [36]: df = DataFrame(np.random.randn(10, 4))
In [37]: df.columns = [np.random.choice(['a', 'b'], size=4).tolist(), np.random.choice(['c', 'd'], size=4)]
In [38]: df.columns.names = ['A', 'B']
In [39]: df
Out[39]:
A b a
B d d d d
0 -1.406 0.548 -0.635 0.576
1 -0.212 -0.583 1.012 -1.377
2 0.951 -0.349 -0.477 -1.230
3 0.451 -0.168 0.949 0.545
4 -0.362 -0.855 1.676 -2.881
5 1.283 1.027 0.085 -1.282
6 0.583 -1.406 0.327 -0.146
7 -0.518 -0.480 0.139 0.851
8 -0.030 -0.630 -1.534 0.534
9 0.246 -1.558 -1.885 -1.543
In [40]: df.xs('a', level='A', axis=1)
Out[40]:
B d d
0 -0.635 0.576
1 1.012 -1.377
2 -0.477 -1.230
3 0.949 0.545
4 1.676 -2.881
5 0.085 -1.282
6 0.327 -0.146
7 0.139 0.851
8 -1.534 0.534
9 -1.885 -1.543
만약 당신이 그것을 유지하기를 원한다면.A
수평을 이루다drop_level
키워드 인수는 v0.13.0)부터만 사용할 수 있습니다.
In [42]: df.xs('a', level='A', axis=1, drop_level=False)
Out[42]:
A a
B d d
0 -0.635 0.576
1 1.012 -1.377
2 -0.477 -1.230
3 0.949 0.545
4 1.676 -2.881
5 0.085 -1.282
6 0.327 -0.146
7 0.139 0.851
8 -1.534 0.534
9 -1.885 -1.543
다중 인덱스 팬더 DataFrame에 액세스하는 방법을 이해하면 이러한 모든 종류의 작업을 수행하는 데 도움이 될 수 있습니다.
이를 코드에 붙여넣어 예제를 생성합니다.
# hierarchical indices and columns
index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]],
names=['year', 'visit'])
columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']],
names=['subject', 'type'])
# mock some data
data = np.round(np.random.randn(4, 6), 1)
data[:, ::2] *= 10
data += 37
# create the DataFrame
health_data = pd.DataFrame(data, index=index, columns=columns)
health_data
다음과 같은 테이블이 제공됩니다.
열별표준접속
health_data['Bob']
type HR Temp
year visit
2013 1 22.0 38.6
2 52.0 38.3
2014 1 30.0 38.9
2 31.0 37.3
health_data['Bob']['HR']
year visit
2013 1 22.0
2 52.0
2014 1 30.0
2 31.0
Name: HR, dtype: float64
# filtering by column/subcolumn - your case:
health_data['Bob']['HR']==22
year visit
2013 1 True
2 False
2014 1 False
2 False
health_data['Bob']['HR'][2013]
visit
1 22.0
2 52.0
Name: HR, dtype: float64
health_data['Bob']['HR'][2013][1]
22.0
행별접속
health_data.loc[2013]
subject Bob Guido Sue
type HR Temp HR Temp HR Temp
visit
1 22.0 38.6 40.0 38.9 53.0 37.5
2 52.0 38.3 42.0 34.6 30.0 37.7
health_data.loc[2013,1]
subject type
Bob HR 22.0
Temp 38.6
Guido HR 40.0
Temp 38.9
Sue HR 53.0
Temp 37.5
Name: (2013, 1), dtype: float64
health_data.loc[2013,1]['Bob']
type
HR 22.0
Temp 38.6
Name: (2013, 1), dtype: float64
health_data.loc[2013,1]['Bob']['HR']
22.0
다중 인덱스 슬라이싱
idx=pd.IndexSlice
health_data.loc[idx[:,1], idx[:,'HR']]
subject Bob Guido Sue
type HR HR HR
year visit
2013 1 22.0 40.0 53.0
2014 1 30.0 52.0 45.0
다음을 사용할 수 있습니다.
>>> df.loc[1]
예
>>> print(df)
result
A B C
1 1 1 6
2 9
2 1 8
2 11
2 1 1 7
2 10
2 1 9
2 12
>>> print(df.loc[1])
result
B C
1 1 6
2 9
2 1 8
2 11
>>> print(df.loc[2, 1])
result
C
1 7
2 10
다른 옵션은 다음과 같습니다.
filter1 = df.index.get_level_values('A') == 1
filter2 = df.index.get_level_values('B') == 4
df.iloc[filter1 & filter2]
Out[11]:
0
A B
1 4 1
사용가능MultiIndex
썰기예를 들어,
arrays = [["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=["A", "B"])
df = pd.DataFrame(np.random.randint(9, size=(8, 2)), index=index, columns=["col1", "col2"])
col1 col2
A B
bar one 0 8
two 4 8
baz one 6 0
two 7 3
foo one 6 8
two 2 6
qux one 7 0
two 6 4
모두 선택하려면 다음 중에서A
그리고.two
부터B
:
df.loc[(slice(None), 'two'), :]
출력:
col1 col2
A B
bar two 4 8
baz two 7 3
foo two 2 6
qux two 6 4
선택방법bar
그리고.baz
부터A
그리고.two
부터B
:
df.loc[(['bar', 'baz'], 'two'), :]
출력:
col1 col2
A B
bar two 4 8
baz two 7 3
언급URL : https://stackoverflow.com/questions/18835077/selecting-from-multi-index-pandas
'prosource' 카테고리의 다른 글
스레드를 생성할 때 CPU 선호도 설정 (0) | 2023.10.20 |
---|---|
XML 문서를 병렬화하는 방법 (0) | 2023.10.20 |
파일 변경 시 노드 다시 시작 (0) | 2023.10.20 |
포맷 방법 BEGIN...SQL과 함께 PDO를 사용하는 END 문? (0) | 2023.10.20 |
DateTime 간의 차이.구문 분석 및 변환.현재 시간까지? (0) | 2023.10.20 |