Pandas에서 공백 값을 NaN으로 바꾸기
문제
Pandas 데이터 프레임에서 공백 값을 찾아 NaN으로 바꾸는 것은 어려울 수 있습니다. 목표는 빈 문자열 값이 있는 데이터프레임을 NaN 값이 있는 데이터프레임으로 변환하여 잠재적으로 데이터 처리 및 분석을 향상시키는 것입니다.
해결책
df.replace() 메서드는 다음과 같은 우아한 솔루션을 제공합니다.
<code class="python">df.replace(r'^\s*$', np.nan, regex=True)</code>
이 정규식 패턴에서 ^는 문자열의 시작 부분과 일치하고, s*는 0개 이상의 공백 문자와 일치하며, $는 문자열의 끝과 일치합니다. 따라서 이 정규 표현식은 완전히 공백 또는 빈 문자열로 구성된 문자열을 검사합니다.
구현
이 솔루션을 예제 데이터 프레임에 적용하면:
<code class="python">df = pd.DataFrame([ [-0.532681, 'foo', 0], [1.490752, 'bar', 1], [-1.387326, 'foo', 2], [0.814772, 'baz', ' '], [-0.222552, ' ', 4], [-1.176781, 'qux', ' '], ], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06')) result = df.replace(r'^\s*$', np.nan, regex=True) print(result)</code>
이렇게 하면 원하는 출력:
A B C 2000-01-01 -0.532681 foo 0 2000-01-02 1.490752 bar 1 2000-01-03 -1.387326 foo 2 2000-01-04 0.814772 baz NaN 2000-01-05 -0.222552 NaN 4 2000-01-06 -1.176781 qux NaN
개선
Temak에서 지적한 대로 유효한 데이터에 공백이 포함될 수 있는 경우 정규식 패턴을 r'^s $'로 수정하여 구성된 문자열만 일치시킬 수 있습니다. 완전히 공백:
<code class="python">df.replace(r'^\s+$', np.nan, regex=True)</code>
위 내용은 Pandas 데이터 프레임에서 공백 값을 NaN으로 어떻게 바꾸나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

contiguousUousUousUlorAllocationScrucialForraysbecauseItAllowsOfficationAndFastElementAccess.1) ItenableSconstantTimeAccess, o (1), DuetodirectAddressCalculation.2) Itimprovesceeffiency theMultipleementFetchespercacheline.3) Itsimplififiesmomorym

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.