판다 데이터 프레임 내의 열을 int에서 string으로 변환
저는 int와 str 데이터 열이 혼합된 팬더의 데이터 프레임을 가지고 있습니다.먼저 데이터 프레임 내의 열을 연결하고 싶습니다.그러기 위해서는 변환해야 합니다.int
의 칼럼.str
저는 다음과 같이 하려고 노력했습니다.
mtrx['X.3'] = mtrx.to_string(columns = ['X.3'])
또는
mtrx['X.3'] = mtrx['X.3'].astype(str)
그러나 두 경우 모두 작동하지 않으며 "'str' 및 'int' 개체를 연결할 수 없습니다."라는 오류 메시지가 나타납니다.연결 2str
열은 완벽하게 잘 작동합니다.
In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))
In [17]: df
Out[17]:
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
In [18]: df.dtypes
Out[18]:
A int64
B int64
dtype: object
열 변환
In [19]: df['A'].apply(str)
Out[19]:
0 0
1 2
2 4
3 6
4 8
Name: A, dtype: object
In [20]: df['A'].apply(str)[0]
Out[20]: '0'
결과를 다시 할당하는 것을 잊지 마십시오.
df['A'] = df['A'].apply(str)
전체 프레임 변환
In [21]: df.applymap(str)
Out[21]:
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'
df = df.applymap(str)
DataFrame 열의 데이터 유형 변경:
들여쓰기:
df.column_name = df.column_name.astype(np.int64)
대상:
df.column_name = df.column_name.astype(str)
경고: 지정된 솔루션(유형() 및 apply()) 모두 nan 또는 None 형식의 NULL 값을 유지하지 않습니다.
import pandas as pd
import numpy as np
df = pd.DataFrame([None,'string',np.nan,42], index=[0,1,2,3], columns=['A'])
df1 = df['A'].astype(str)
df2 = df['A'].apply(str)
print df.isnull()
print df1.isnull()
print df2.isnull()
저는 이것이 to_string()의 구현에 의해 해결된다고 생각합니다.
다음 코드를 사용합니다.
df.column_name = df.column_name.astype('str')
열을 문자열로 변환하는 네 가지 방법이 있습니다.
1. astype(str)
df['column_name'] = df['column_name'].astype(str)
2. values.astype(str)
df['column_name'] = df['column_name'].values.astype(str)
3. map(str)
df['column_name'] = df['column_name'].map(str)
4. apply(str)
df['column_name'] = df['column_name'].apply(str)
각 유형의 성능을 살펴보겠습니다.
#importing libraries
import numpy as np
import pandas as pd
import time
#creating four sample dataframes using dummy data
df1 = pd.DataFrame(np.random.randint(1, 1000, size =(10000000, 1)), columns =['A'])
df2 = pd.DataFrame(np.random.randint(1, 1000, size =(10000000, 1)), columns =['A'])
df3 = pd.DataFrame(np.random.randint(1, 1000, size =(10000000, 1)), columns =['A'])
df4 = pd.DataFrame(np.random.randint(1, 1000, size =(10000000, 1)), columns =['A'])
#applying astype(str)
time1 = time.time()
df1['A'] = df1['A'].astype(str)
print('time taken for astype(str) : ' + str(time.time()-time1) + ' seconds')
#applying values.astype(str)
time2 = time.time()
df2['A'] = df2['A'].values.astype(str)
print('time taken for values.astype(str) : ' + str(time.time()-time2) + ' seconds')
#applying map(str)
time3 = time.time()
df3['A'] = df3['A'].map(str)
print('time taken for map(str) : ' + str(time.time()-time3) + ' seconds')
#applying apply(str)
time4 = time.time()
df4['A'] = df4['A'].apply(str)
print('time taken for apply(str) : ' + str(time.time()-time4) + ' seconds')
산출량
time taken for astype(str): 5.472359895706177 seconds
time taken for values.astype(str): 6.5844292640686035 seconds
time taken for map(str): 2.3686647415161133 seconds
time taken for apply(str): 2.39758563041687 seconds
여러 번 실행하는 경우 각 매개 변수에 대한 시간이 다를 수 있습니다.평균 map(str)
그리고.apply(str)
나머지 두 기술에 비해 시간이 적게 걸립니다.
나는 이것이 오래된 질문이라는 것을 알지만, 그것이 df 문자열 변환에 대해 가장 먼저 떠오르는 것이기 때문에 IMHO는 최신일 것입니다.
실제 dtype을 (객체가 아닌) 문자열로 사용하거나 df에서 날짜/시간 변환을 처리해야 하는 경우 또는 naN/None이 있는 경우.위의 내용 중 하나도 작동하지 않습니다.
다음을 사용해야 합니다.
df.astype('string')
다음 df에서 결과를 비교할 수 있습니다.
import pandas as pd
import numpy as np
from datetime import datetime
# Example dataframe
min_index = datetime(2050, 5, 2, 0, 0, 0)
max_index = datetime(2050, 5, 3, 23, 59, 0)
df = pd.DataFrame(data=pd.date_range(start=min_index, end=max_index, freq = "H"), columns=["datetime"])
df["hours"] = df["datetime"].dt.hour
df["day_name"] = df["datetime"].dt.strftime("%A")
df["numeric_cat"] = [np.random.choice([0,1,2]) for a in range(df.shape[0])]
# Add missing values:
df = df.mask(np.random.random(df.shape) < 0.1)
# str
df1 = df.astype(str) #same pb with apply(str)
df1.isnull().sum().sum() # return 0 which is wrong
df1.info() #gives you a dtype object
# string
df2 = df.astype('string')
df2.isnull().sum().sum() # return the correct nb of missing value
df2.info() #gives you a dtype string
참고용으로 말입니다.
위의 모든 답변은 데이터 프레임의 경우 작동합니다.그러나 열을 생성/수정하는 동안 람다를 사용하는 경우 다른 사용자가 위의 답변을 사용할 수 없습니다. 이 답변은 판다 열 대신 int 속성으로 간주되기 때문입니다.문자열로 만들려면 str(target_attribute )을 사용해야 합니다.아래의 예를 참고하시기 바랍니다.
def add_zero_in_prefix(df):
if(df['Hour']<10):
return '0' + str(df['Hour'])
data['str_hr'] = data.apply(add_zero_in_prefix, axis=1)
언급URL : https://stackoverflow.com/questions/17950374/converting-a-column-within-pandas-dataframe-from-int-to-string
'programing' 카테고리의 다른 글
스프링 부트에서 프로필을 기반으로 선택적 테스트를 실행/해제하는 방법 (0) | 2023.07.18 |
---|---|
git log에서 지점 이름을 표시하려면 어떻게 해야 합니까? (0) | 2023.07.18 |
Mongoose가 배열 내에서 문서를 삭제(풀)하고 개체와 함께 작동하지 않습니다.아이디 (0) | 2023.07.18 |
PL/SQL의 숨겨진 기능 (0) | 2023.07.18 |
SQL*Plus에서 잘못된 형식 지정 (0) | 2023.07.18 |