다음과 같은 DataFrame이 있습니다.
| Age | Married | OwnsHouse |
| 23 | True | False |
| 35 | True | True |
| 14 | False | False |
| 27 | True | True |
나는 결혼하고 집을 소유 한 사람 중 가장 높은 나이를 찾고 싶습니다. 여기에 대한 답은 35가 될 것입니다. 내 첫 번째 생각은 다음과 같습니다.
df_subset = df[df['Married'] == True and df['OwnsHouse'] == True]
max_age = df_subset.max()
그러나 데이터 세트가 크며 (50MB) 데이터 세트를 두 번 통과하므로 계산 비용이 많이 들지 않을까 걱정됩니다.
두 번째 생각은 다음과 같습니다.
max_age = 0
for index, row in df.iterrows():
if(row[index]['Married] and row['index']['OwnsHouse'] and row[index]['Age] > max_age):
max_age = row[index]['Age']
이 작업을 수행하는 더 빠른 방법이 있습니까?
첫 번째 접근 방식은 견고하지만 다음은 간단한 옵션입니다.
df[df['Married'] & df['OwnsHouse']].max()
Age 35.0
Married 1.0
OwnsHouse 1.0
dtype: float64
또는 나이 :
df.loc[df['Married'] & df['OwnsHouse'], 'Age'].max()
# 35
부울 열이 여러 개인 경우 좀 더 확장 가능한 것을 제안합니다.
df[df[['Married', 'OwnsHouse']].all(axis=1)].max()
Age 35.0
Married 1.0
OwnsHouse 1.0
dtype: float64
어디,
df[['Married', 'OwnsHouse']].all(axis=1)
0 False
1 True
2 False
3 True
dtype: bool
그것은 다음과 같습니다.
df['Married'] & df['OwnsHouse']
0 False
1 True
2 False
3 True
dtype: bool
그러나 N 개의 부울 마스크의 AND를 수동으로 찾는 대신에 .all
그렇게하십시오.
query
또 다른 옵션입니다.
df.query("Married and OwnsHouse")['Age'].max()
# 35
마스크를 계산하는 중간 단계가 필요하지 않습니다.
귀하의 방법은 충분히 빠르지 만 미세 최적화를 원한다면 다음과 같은 numpy 옵션이 더 있습니다.
# <= 0.23
df[(df['Married'].values & df['OwnsHouse'].values)].max()
df[df[['Married', 'OwnsHouse']].values.all(axis=1)].max()
# 0.24+
df[(df['Married'].to_numpy() & df['OwnsHouse'].to_numpy())].max()
df[df[['Married', 'OwnsHouse']].to_numpy().all(axis=1)].max()
Age 35.0
Married 1.0
OwnsHouse 1.0
dtype: float64
당신은 아마도 나이를 원할 것입니다. 이 작업을 수행
df.loc[(df['Married'].to_numpy() & df['OwnsHouse'].to_numpy()), 'Age'].max()
# 35
좀 더 numpy를 원한다면 다음을 수행하십시오.
df.loc[(
df['Married'].to_numpy() & df['OwnsHouse'].to_numpy()), 'Age'
].to_numpy().max()
# 35
또는 더 나은 방법은 판다를 버리고
df['Age'].to_numpy()[df['Married'].to_numpy() & df['OwnsHouse'].to_numpy()].max()
# 35
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다