Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python Pandas - 다중 인덱스에서 모든 수준이 NaN인 경우 값 삭제

<시간/>

다중 인덱스에서 레벨이 NaN일 때 값을 삭제하려면 multiIndex.dropna()를 사용하세요. 방법. 매개변수 설정 방법 모든 값 포함 .

먼저 필요한 라이브러리를 가져옵니다. -

import pandas as pd
import numpy as np

일부 NaN 값으로 다중 인덱스를 만듭니다. 이름 매개변수는 인덱스의 레벨 이름을 설정합니다 -

multiIndex = pd.MultiIndex.from_arrays([[5, 10], [np.nan, 20], [25, np.nan], [35, 40]],names=['a', 'b', 'c', 'd'])

다중 인덱스에서 임의의 수준이 NaN인 경우 값을 삭제합니다. 단일 NaN 값이 있더라도 dropna()는 모든 값을 삭제합니다. dropna()의 "how" 매개변수는 이것에 대해 "any" 값과 함께 사용됩니다 -

print("\nDropping the value when any level is NaN...\n",multiIndex.dropna(how='any'))

예시

다음은 코드입니다 -

import pandas as pd
import numpy as np

# Create a multi-index with some NaN values
# The names parameter sets the names for the levels in the index
multiIndex = pd.MultiIndex.from_arrays([[5, 10], [np.nan, 20], [25, np.nan], [35, 40]],names=['a', 'b', 'c', 'd'])

# display the multi-index
print("Multi-index...\n", multiIndex)

# Drop the value when any level is NaN in a Multi-index
# Even with a single NaN value, the dropna() will drop all the values
# The "how" parameter of the dropna() is used with the value "any" for this
print("\nDropping the value when any level is NaN...\n",multiIndex.dropna(how='any'))
에 대해 "any" 값과 함께 사용됩니다.

출력

이것은 다음과 같은 출력을 생성합니다 -

Multi-index...
MultiIndex([( 5, nan, 25.0, 35),(10, 20.0, nan, 40)],names=['a', 'b', 'c', 'd'])

Dropping the value when any level is NaN...
MultiIndex([], names=['a', 'b', 'c', 'd'])