programing

Pandas DataFrame 헤더에서 공백을 제거하려면 어떻게 해야 합니까?

itmemos 2023. 8. 30. 21:17
반응형

Pandas DataFrame 헤더에서 공백을 제거하려면 어떻게 해야 합니까?

일부 열 제목에 공백이 추가된 Excel 파일의 데이터를 구문 분석하고 있습니다.

결과 데이터 프레임의 열을 확인할 때,df.columns알겠습니다.

Index(['Year', 'Month ', 'Value'])
                     ^
#                    Note the unwanted trailing space on 'Month '

따라서 다음을 수행할 수 없습니다.

df["Month"]

"월"이 아니라 "월"을 요청했기 때문에 열을 찾을 수 없다고 표시하기 때문입니다.

그렇다면, 제 질문은 어떻게 하면 칼럼 제목에서 불필요한 공백을 제거할 수 있을까요?

다음에 기능을 제공할 수 있습니다.rename방법. 그str.strip()방법은 사용자가 원하는 작업을 수행해야 합니다.

In [5]: df
Out[5]: 
   Year  Month   Value
0     1       2      3

[1 rows x 3 columns]

In [6]: df.rename(columns=lambda x: x.strip())
Out[6]: 
   Year  Month  Value
0     1      2      3

[1 rows x 3 columns]

참고: 이것은 다음을 반환합니다.DataFrame화면에 출력으로 표시되지만 변경 내용이 실제로 열에 설정되어 있지 않습니다.변경하려면 메서드 체인에서 이를 사용하거나 다시 할당합니다.df변수:

df = df.rename(columns=lambda x: x.strip())

버전 0.16.1 이후에는 다음 열을 호출할 수 있습니다.

df.columns = df.columns.str.strip()

다음은 작은 예입니다.

In [5]:
df = pd.DataFrame(columns=['Year', 'Month ', 'Value'])
print(df.columns.tolist())
df.columns = df.columns.str.strip()
df.columns.tolist()

['Year', 'Month ', 'Value']
Out[5]:
['Year', 'Month', 'Value']

타이밍

In[26]:
df = pd.DataFrame(columns=[' year', ' month ', ' day', ' asdas ', ' asdas', 'as ', '  sa', ' asdas '])
df
Out[26]: 
Empty DataFrame
Columns: [ year,  month ,  day,  asdas ,  asdas, as ,   sa,  asdas ]


%timeit df.rename(columns=lambda x: x.strip())
%timeit df.columns.str.strip()
1000 loops, best of 3: 293 µs per loop
10000 loops, best of 3: 143 µs per loop

그렇게str.strip최대 2배 더 빠릅니다. 더 큰 dfs에 대해 더 잘 확장될 것으로 예상합니다.

CSV 형식을 사용하여 Excel에서 내보내고 Pandas DataFrame으로 읽을 경우 다음을 지정할 수 있습니다.

skipinitialspace=True

방문할 때pd.read_csv.

설명서에서 다음을 참조하십시오.

초기 공간 건너뛰기: bool, 기본값 False

Skip spaces after delimiter.

만약 당신이 그것을 할 수 있는 깨지지 않는 방법을 찾고 있다면, 저는 다음을 제안하고 싶습니다.

data_frame.rename(columns=lambda x: x.strip() if isinstance(x, str) else x, inplace=True)

사실은 그것을 할 수 있습니다.

df.rename(str.strip, axis = 'columns')

이것은 여기 판다 설명서에 나와 있습니다.

언급URL : https://stackoverflow.com/questions/21606987/how-can-i-strip-the-whitespace-from-pandas-dataframe-headers

반응형