반응형
int64
볼륨 측정 열이있는 xiv
라는 pandas DataFrame 개체가 있습니다.
In[]: xiv['Volume'].head(5)
Out[]:
0 252000
1 484000
2 62000
3 168000
4 232000
Name: Volume, dtype: int64
In[]: xiv['Volume'] = pd.to_numeric(xiv['Volume'])
In[]: xiv['Volume'].dtypes
Out[]:
dtype('int64')
또는...
In[]: xiv['Volume'] = pd.to_numeric(xiv['Volume'])
Out[]: ###omitted for brevity###
In[]: xiv['Volume'].dtypes
Out[]:
dtype('int64')
In[]: xiv['Volume'] = xiv['Volume'].apply(pd.to_numeric)
In[]: xiv['Volume'].dtypes
Out[]:
dtype('int64')
또한 별도의 pandas Series
를 만들고 해당 Series에 위에 나열된 방법을 사용하여 x [ 'Volume']
개체에 다시 할당하려고 시도했습니다. > pandas.core.series.Series 객체.
그러나 numpy
패키지의 float64
유형을 사용하여이 문제에 대한 해결책을 찾았습니다. 이것은 작동하지만 왜 다른지 모르겠습니다 < / em> .
In[]: xiv['Volume'] = xiv['Volume'].astype(np.float64)
In[]: xiv['Volume'].dtypes
Out[]:
dtype('float64')
누군가 pandas
라이브러리를 사용하여 numpy
라이브러리가 float64
클래스로 쉽게 수행하는 작업을 수행하는 방법을 설명 할 수 있습니까? 즉, xiv
DataFrame의 열을 float64
로 변환합니다.
해결 방법
데모:
In [90]: df = pd.DataFrame(np.random.randint(10**5,10**7,(5,3)),columns=list('abc'), dtype=np.int64)
In [91]: df
Out[91]:
a b c
0 9059440 9590567 2076918
1 5861102 4566089 1947323
2 6636568 162770 2487991
3 6794572 5236903 5628779
4 470121 4044395 4546794
In [92]: df.dtypes
Out[92]:
a int64
b int64
c int64
dtype: object
In [93]: df['a'] = df['a'].astype(float)
In [94]: df.dtypes
Out[94]:
a float64
b int64
c int64
dtype: object
object
(문자열) dtype에는 작동하지 않으며 숫자로 변환 할 수 없습니다 :
In [95]: df.loc[1, 'b'] = 'XXXXXX'
In [96]: df
Out[96]:
a b c
0 9059440.0 9590567 2076918
1 5861102.0 XXXXXX 1947323
2 6636568.0 162770 2487991
3 6794572.0 5236903 5628779
4 470121.0 4044395 4546794
In [97]: df.dtypes
Out[97]:
a float64
b object
c int64
dtype: object
In [98]: df['b'].astype(float)
...
skipped
...
ValueError: could not convert string to float: 'XXXXXX'
In [99]: df['b'] = pd.to_numeric(df['b'], errors='coerce')
In [100]: df
Out[100]:
a b c
0 9059440.0 9590567.0 2076918
1 5861102.0 NaN 1947323
2 6636568.0 162770.0 2487991
3 6794572.0 5236903.0 5628779
4 470121.0 4044395.0 4546794
In [101]: df.dtypes
Out[101]:
a float64
b float64
c int64
dtype: object
참조 페이지 https://stackoverflow.com/questions/40095712
반응형
'파이썬' 카테고리의 다른 글
파이썬에서 n 개의 문자로 채우는 방법 (0) | 2020.10.27 |
---|---|
파이썬 Python의 RotatingFileHandler 사용 방법 (0) | 2020.10.27 |
파이썬 Django Forms에서 CSS 클래스 정의 (0) | 2020.10.27 |
파이썬 클래스 인스턴스 Python 목록 정렬 (0) | 2020.10.27 |
파이썬에서 문자열의 마지막 문자를 반환 (0) | 2020.10.27 |
댓글