sourcecode

판다의 기둥 유형 변경

copyscript 2022. 10. 7. 22:11
반응형

판다의 기둥 유형 변경

다음 목록에서 DataFrame을 만들었습니다.

table = [
    ['a',  '1.2',  '4.2' ],
    ['b',  '70',   '0.03'],
    ['x',  '5',    '0'   ],
]

df = pd.DataFrame(table)

열을 특정 유형으로 변환하려면 어떻게 해야 합니까?이 경우 2열과 3열을 플로트로 변환하고 싶습니다.

Data Frame으로 변환할 때 유형을 지정할 수 있는 방법이 있습니까?아니면 먼저 Data Frame을 만든 후 열을 반복하여 각 열의 유형을 변경하는 것이 더 좋습니까?이상적으로는 수백 개의 열이 있을 수 있고 어떤 열의 유형을 정확하게 지정하고 싶지 않기 때문에 이 작업을 동적으로 수행하려고 합니다.각 열에 동일한 유형의 값이 포함되어 있다는 것만 보증할 수 있습니다.

판다의 유형을 변환하는 데는 네 가지 주요 옵션이 있습니다.

  1. to_numeric() - 비문자형(예: 문자열)을 적절한 숫자형으로 안전하게 변환하는 기능을 제공합니다.(및 을 참조해 주세요).

  2. astype() - (거의) 모든 타입을 (거의) 다른 타입으로 변환합니다(반드시 그렇게 하는 것이 현명하지 않더라도).또한 범주 유형으로 변환할 수 있습니다(매우 유용).

  3. infer_objects() - Python 오브젝트를 보유한 오브젝트 컬럼을 가능한 팬더 타입으로 변환하는 유틸리티 방식.

  4. convert_dtypes() - Data Frame 열을 지원하는 "최상의" dtype으로 변환합니다.pd.NA('여보세요')

이러한 각 방법의 상세한 설명과 사용법에 대해서는, 계속 읽어 주세요.


1. to_numeric()

DataFrame의 1개 이상의 열을 수치로 변환하는 가장 좋은 방법은 를 사용하는 것입니다.

이 함수는 필요에 따라 숫자 이외의 객체(문자열 등)를 정수 또는 부동소수점 숫자로 변경하려고 합니다.

기본 사용법

에 대한 입력은 DataFrame의 Series 또는 단일 컬럼입니다.

>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0      8
1      6
2    7.5
3      3
4    0.9
dtype: object

>>> pd.to_numeric(s) # convert everything to float values
0    8.0
1    6.0
2    7.5
3    3.0
4    0.9
dtype: float64

보시다시피 새 시리즈가 반환됩니다.이 출력을 계속 사용하려면 변수 또는 열 이름에 할당해야 합니다.

# convert Series
my_series = pd.to_numeric(my_series)

# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])

또한 다음 방법으로 DataFrame의 여러 열을 변환할 수도 있습니다.

# convert all columns of DataFrame
df = df.apply(pd.to_numeric) # convert all columns of DataFrame

# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)

당신의 가치를 모두 바꿀 수 있는 한, 아마도 그것만 있으면 될 것입니다.

에러 처리

그러나 일부 값을 숫자 유형으로 변환할 수 없는 경우에는 어떻게 해야 합니까?

to_numeric() 또,errors을 non-timeout으로 할 수 NaN또는 단순히 이러한 값이 포함된 열을 무시합니다.

일련의 문자열을 .s"Dtype" (dtype) :

>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0         1
1         2
2       4.7
3    pandas
4        10
dtype: object

기본 동작은 값을 변환할 수 없는 경우 상승합니다.이 경우 문자열 'pandas'에 대처할 수 없습니다.

>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string

실패하기보다는 '판다'를 결측/불량 수치로 간주할 수 있습니다.하지 않은 을 강제로 할 수 .NaN를 사용하여 다음과 같이errors다음 중 하나:

>>> pd.to_numeric(s, errors='coerce')
0     1.0
1     2.0
2     4.7
3     NaN
4    10.0
dtype: float64

의 세 입니다.errors했을 때 입니다.

>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched

이 마지막 옵션은 전체 DataFrame을 변환하는 데 특히 유용하지만 어떤 열을 숫자 유형으로 확실하게 변환할 수 있는지 알 수 없습니다.이 경우는, 다음과 같이 기입해 주세요.

df.apply(pd.to_numeric, errors='ignore')

이 함수는 DataFrame의 각 열에 적용됩니다.숫자 유형으로 변환할 수 있는 열은 변환되지만 변환할 수 없는 열(예: 숫자가 아닌 문자열 또는 날짜가 포함됨)은 그대로 유지됩니다.

다운캐스팅

디폴트로는 와의 변환에 의해int64 ★★★★★★★★★★★★★★★★★」float64)

을 하고 , 더 더 한 d타입, 예를 들면 통통원 typetype만 typetype typetype typetype을 dtype a that 、 음음음음 음음음 음을 음을 음을 음을 음 음 음 음 a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a that that that that thatfloat32 , 「」int8

to_numeric() 다음 중 하나로 다운다운할 수 있는 옵션이 있습니다.'integer','signed','unsigned','float' 시리즈가 s수수: :

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

을 하다'integer'그럼 값을 유지할 수 있는 최소 정수를 사용합니다.

>>> pd.to_numeric(s, downcast='integer')
0    1
1    2
2   -7
dtype: int8

을 하다'float'마찬가지로 일반 부동 유형보다 작은 부동 유형을 선택합니다.

>>> pd.to_numeric(s, downcast='float')
0    1.0
1    2.0
2   -7.0
dtype: float32

2. astype()

이 메서드를 사용하면 DataFrame 또는 Series에서 원하는 dtype을 명시적으로 지정할 수 있습니다.어떤 타입에서 다른 타입으로 시도하거나 할 수 있다는 점에서 매우 다재다능합니다.

기본 사용법

. NumPy dtype)을할 수 . NumPy dtype은 NumPy dtype입니다.np.int16Python ( ( : bool ) 또)))))))))))))))) ( : )typetypetypetypetypetypetypetypetype dtype )

변환할 객체의 메서드를 호출하면 변환이 시도됩니다.

# convert all DataFrame columns to the int64 dtype
df = df.astype(int)

# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})

# convert Series to float16 type
s = s.astype(np.float16)

# convert Series to Python strings
s = s.astype(str)

# convert Series to categorical type - see docs for more details
s = s.astype('category')

"try"라고 말한 것에 주의해 주세요.는 Series 또는 DataFrame에서 값을 변환하는 방법을 모르면 오류가 발생합니다.예를 들어 다음과 같은 경우NaN ★★★★★★★★★★★★★★★★★」inf값을 정수로 변환하려고 하면 오류가 발생합니다.

0에서는, 이는, 「0.20.0」으로 할 수 .errors='ignore' 오브젝트는 않고됩니다. 원래 오브젝트는 손대지 않고 반환됩니다.

조심하세요.

astype() 강력하지만 때로는 값을 "불필요하게" 변환할 수 있습니다.예를 들어 다음과 같습니다.

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

이것들은 작은 정수이기 때문에, 메모리를 절약하기 위해서 부호 없는 8비트 타입으로 변환하는 것은 어떻습니까?

>>> s.astype(np.uint8)
0      1
1      2
2    249
dtype: uint8

변환은 성공했지만 -7은 249로 반올림되었습니다8(2~7).

를 하려고 합니다.pd.to_numeric(s, downcast='unsigned')대신 이 오류를 방지하는 데 도움이 됩니다.


3. infer_objects()

판다 0.21.0 버전에서는 객체 데이터형이 있는 DataFrame의 열을 보다 구체적인 유형(소프트 변환)으로 변환하는 방법이 도입되었습니다.

예를 들어, 두 개의 개체 유형 열이 있는 DataFrame이 있습니다.하나는 실제 정수를 보관 유지하고 다른 하나는 정수를 나타내는 문자열을 보관합니다.

>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a    object
b    object
dtype: object

를 사용하여 열 'a' 유형을 int64로 변경할 수 있습니다.

>>> df = df.infer_objects()
>>> df.dtypes
a     int64
b    object
dtype: object

열 'b'는 값이 정수가 아닌 문자열이므로 그대로 남아 있습니다.타입으로 는, 「」를 사용할 수 .df.astype(int)★★★★★★ 。


4. convert_dtypes()

버전 1.0 이상에는 Series 열과 DataFrame 열을 가능한 한 최적의 dtype으로 변환하는 방법이 포함되어 있습니다.pd.NA결측값

베스트 포서블예를 들어, 모든 값이 정수(또는 결측값)인 경우 Python 정수 객체의 객체 열은 다음과 같이 변환됩니다.Int64, NumPy int32, dtype, dtype이 Int32.

델의 ★★와object 프레임df을 사용하다

>>> df.convert_dtypes().dtypes                                             
a     Int64
b    string
dtype: object

에 'a'로 되었습니다.Int64할 수 있음)int64를 참조해 주세요.

'열에는 판다의 'b'로 바뀌었다.stringdtype을 지정합니다.

기본적으로 이 메서드는 각 열의 개체 값에서 유형을 추론합니다.할 수 있는 은, 「이것」을 입니다.infer_objects=False:

>>> df.convert_dtypes(infer_objects=False).dtypes                          
a    object
b    string
dtype: object

이제 열 'a'는 물체 열로 남았습니다: 판다는 그것이 'integer' 열로 묘사될 수 있다는 것을 알고 있었지만, 정확히 어떤 종류의 정수를 가져야 하는지 추론하지 못했기 때문에 그것을 변환하지 않았습니다.열 'b'는 'string' 값을 유지하는 것으로 인식되었기 때문에 다시 'string' dtype으로 변환되었습니다.

이건 어때?

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df
Out[16]: 
  one  two three
0   a  1.2   4.2
1   b   70  0.03
2   x    5     0

df.dtypes
Out[17]: 
one      object
two      object
three    object

df[['two', 'three']] = df[['two', 'three']].astype(float)

df.dtypes
Out[19]: 
one       object
two      float64
three    float64

아래 코드는 열의 데이터 유형을 변경합니다.

df[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')

데이터 유형 대신 데이터 유형을 지정할 수 있습니다. str, filename, int 등과 같은 항목을 지정하십시오.

특정 열만 지정하면 되고 명시적으로 하고 싶을 때는 (DOCS LOCATION별로) 다음을 사용했습니다.

dataframe = dataframe.astype({'col_name_1':'int','col_name_2':'float64', etc. ...})

그래서 원래 질문을 사용하여 컬럼 이름을 지정하면...

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col_name_1', 'col_name_2', 'col_name_3'])
df = df.astype({'col_name_2':'float64', 'col_name_3':'float64'})

다음은 DataFrame과 열 목록을 인수로 사용하여 열에 있는 모든 데이터를 숫자로 강제하는 함수입니다.

# df is the DataFrame, and column_list is a list of columns as strings (e.g ["col1","col2","col3"])
# dependencies: pandas

def coerce_df_columns_to_numeric(df, column_list):
    df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')

예를 들어 다음과 같습니다.

import pandas as pd

def coerce_df_columns_to_numeric(df, column_list):
    df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col1','col2','col3'])

coerce_df_columns_to_numeric(df, ['col2','col3'])

팬더 > = 1.0

여기 판다의 가장 중요한 변화를 요약한 차트가 있습니다.

여기에 이미지 설명 입력

입니다..astype(str)그림에는 나와 있지 않습니다.

"하드" 변환과 "소프트" 변환

이 컨텍스트에서 "변환"은 텍스트 데이터를 실제 데이터 유형으로 변환(하드 변환)하거나 개체 열의 데이터에 대해 더 적절한 데이터 유형을 추론(소프트 변환)하는 것을 나타낼 수 있습니다.차이점을 설명하기 위해

df = pd.DataFrame({'a': ['1', '2', '3'], 'b': [4, 5, 6]}, dtype=object)
df.dtypes                                                                  

a    object
b    object
dtype: object

# Actually converts string to numeric - hard conversion
df.apply(pd.to_numeric).dtypes                                             

a    int64
b    int64
dtype: object

# Infers better data types for object data - soft conversion
df.infer_objects().dtypes                                                  

a    object  # no change
b     int64
dtype: object

# Same as infer_objects, but converts to equivalent ExtensionType
df.convert_dtypes().dtypes                                                     

각각 열에 대한 데이터 유형이 서로 다른 두 개의 데이터 프레임을 생성한 다음 함께 추가하는 것은 어떻습니까?

d1 = pd.DataFrame(columns=[ 'float_column' ], dtype=float)
d1 = d1.append(pd.DataFrame(columns=[ 'string_column' ], dtype=str))

결과.

In[8}:  d1.dtypes
Out[8]: 
float_column     float64
string_column     object
dtype: object

데이터 프레임이 생성되면 첫 번째 열에 부동소수점 변수를 입력하고 두 번째 열에 문자열(또는 원하는 데이터 유형)을 입력할 수 있습니다.

df = df.astype({"columnname": str})

#예: 열 유형을 문자열 #df로 변경하기 위한 데이터 프레임입니다.

df.info()은 float64라는 temp의 초기 데이터 유형을 제공합니다.

 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   date    132 non-null    object 
 1   temp    132 non-null    float64

다음 코드를 사용하여 데이터 유형을 int64로 변경합니다.

df['temp'] = df['temp'].astype('int64')

df.info()을 다시 실행하면 다음과 같이 표시됩니다.

  #   Column  Non-Null Count  Dtype 
 ---  ------  --------------  ----- 
  0   date    132 non-null    object
  1   temp    132 non-null    int64 

이것은 열 temp의 데이터 유형을 성공적으로 변경했음을 나타냅니다.해피 코딩!

.0부터 【1.0.0】가 있습니다.pandas.DataFrame.convert_dtypes어떤 타입으로 변환할지도 제어할 수 있습니다!

In [40]: df = pd.DataFrame(
    ...:     {
    ...:         "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
    ...:         "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
    ...:         "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
    ...:         "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
    ...:         "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
    ...:         "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
    ...:     }
    ...: )

In [41]: dff = df.copy()

In [42]: df 
Out[42]: 
   a  b      c    d     e      f
0  1  x   True    h  10.0    NaN
1  2  y  False    i   NaN  100.5
2  3  z    NaN  NaN  20.0  200.0

In [43]: df.dtypes
Out[43]: 
a      int32
b     object
c     object
d     object
e    float64
f    float64
dtype: object

In [44]: df = df.convert_dtypes()

In [45]: df.dtypes
Out[45]: 
a      Int32
b     string
c    boolean
d     string
e      Int64
f    float64
dtype: object

In [46]: dff = dff.convert_dtypes(convert_boolean = False)

In [47]: dff.dtypes
Out[47]: 
a      Int32
b     string
c     object
d     string
e      Int64
f    float64
dtype: object

74개의 객체 열과 2개의 Int 열의 데이터 프레임과 같은 다양한 객체 열이 있는 경우 각 값에 단위를 나타내는 문자가 있습니다.

import pandas as pd 
import numpy as np
dataurl = 'https://raw.githubusercontent.com/RubenGavidia/Pandas_Portfolio.py/main/Wes_Mckinney.py/nutrition.csv'
nutrition = pd.read_csv(dataurl,index_col=[0])
nutrition.head(3)

    name    serving_size    calories    total_fat   saturated_fat   cholesterol sodium  choline folate  folic_acid  ... fat saturated_fatty_acids   monounsaturated_fatty_acids polyunsaturated_fatty_acids fatty_acids_total_trans alcohol ash caffeine    theobromine water
0   Cornstarch  100 g   381 0.1g    NaN 0   9.00 mg 0.4 mg  0.00 mcg    0.00 mcg    ... 0.05 g  0.009 g 0.016 g 0.025 g 0.00 mg 0.0 g   0.09 g  0.00 mg 0.00 mg 8.32 g
1   Nuts, pecans    100 g   691 72g 6.2g    0   0.00 mg 40.5 mg 22.00 mcg   0.00 mcg    ... 71.97 g 6.180 g 40.801 g    21.614 g    0.00 mg 0.0 g   1.49 g  0.00 mg 0.00 mg 3.52 g
2   Eggplant, raw   100 g   25  0.2g    NaN 0   2.00 mg 6.9 mg  22.00 mcg   0.00 mcg    ... 0.18 g  0.034 g 0.016 g 0.076 g 0.00 mg 0.0 g   0.66 g  0.00 mg 0.00 mg 92.30 g
3 rows × 76 columns

nutrition.dtypes
name             object
serving_size     object
calories          int64
total_fat        object
saturated_fat    object
                  ...  
alcohol          object
ash              object
caffeine         object
theobromine      object
water            object
Length: 76, dtype: object

nutrition.dtypes.value_counts()
object    74
int64      2
dtype: int64

모든 열을 수치로 변환하는 좋은 방법은 정규식을 사용하여 단위를 아무것도 바꾸지 않고 열 데이터 유형을 부동으로 변경하는 것입니다.

nutrition.index = pd.RangeIndex(start = 0, stop = 8789, step= 1)
nutrition.set_index('name',inplace = True)
nutrition.replace('[a-zA-Z]','', regex= True, inplace=True)
nutrition=nutrition.astype(float)
nutrition.head(3)

serving_size    calories    total_fat   saturated_fat   cholesterol sodium  choline folate  folic_acid  niacin  ... fat saturated_fatty_acids   monounsaturated_fatty_acids polyunsaturated_fatty_acids fatty_acids_total_trans alcohol ash caffeine    theobromine water
name                                                                                    
Cornstarch  100.0   381.0   0.1 NaN 0.0 9.0 0.4 0.0 0.0 0.000   ... 0.05    0.009   0.016   0.025   0.0 0.0 0.09    0.0 0.0 8.32
Nuts, pecans    100.0   691.0   72.0    6.2 0.0 0.0 40.5    22.0    0.0 1.167   ... 71.97   6.180   40.801  21.614  0.0 0.0 1.49    0.0 0.0 3.52
Eggplant, raw   100.0   25.0    0.2 NaN 0.0 2.0 6.9 22.0    0.0 0.649   ... 0.18    0.034   0.016   0.076   0.0 0.0 0.66    0.0 0.0 92.30
3 rows × 75 columns

nutrition.dtypes
serving_size     float64
calories         float64
total_fat        float64
saturated_fat    float64
cholesterol      float64
                  ...   
alcohol          float64
ash              float64
caffeine         float64
theobromine      float64
water            float64
Length: 75, dtype: object

nutrition.dtypes.value_counts()
float64    75
dtype: int64

이제 데이터셋이 깨끗하여 regex 및 astype()에서만 이 데이터프레임에서 숫자 작업을 수행할 수 있습니다.

cholesterol_mg을 사용하다

nutrition.index = pd.RangeIndex(start = 0, stop = 8789, step= 1)
nutrition.set_index('name',inplace = True)
nutrition.astype(str).replace('[^a-zA-Z]','', regex= True)
units = nutrition.astype(str).replace('[^a-zA-Z]','', regex= True)
units = units.mode()
units = units.replace('', np.nan).dropna(axis=1)
mapper = { k: k + "_" + units[k].at[0] for k in units}
nutrition.rename(columns=mapper, inplace=True)
nutrition.replace('[a-zA-Z]','', regex= True, inplace=True)
nutrition=nutrition.astype(float)

Data Frame으로 변환할 때 유형을 지정할 수 있는 방법이 있습니까?

답변은 Frame 작성 후시 할 수 . 다른 답변은 DataFrame 작성 후 dtype을 변환하지만 작성 시 유형을 지정할 수 있습니다. 중 하나를 합니다.DataFrame.from_records ★★★★★★★★★★★★★★★★★」read_csv(dtype=...)입력 형식에 따라 달라집니다.

빅데이터 메모리 오류를 방지하기 위해 후자가 필요할 수 있습니다.


1. DataFrame.from_records

원하는 열 유형의 구조화된 배열에서 DataFrame을 만듭니다.

x = [['foo', '1.2', '70'], ['bar', '4.2', '5']]

df = pd.DataFrame.from_records(np.array(
    [tuple(row) for row in x], # pass a list-of-tuples (x can be a list-of-lists or 2D array)
    'object, float, int'       # define the column types
))

출력:

>>> df.dtypes
# f0     object
# f1    float64
# f2      int64
# dtype: object

2. read_csv(dtype=...)

는 을 합니다.dtype「」read_csv로드 시 열 유형을 설정합니다.

들어 행과 30M 이 표시됩니다.rating 및 8비트 '''로 지정합니다.genre★★★★★★★★★★★★★★★★★★:

lines = '''
foo,biography,5
bar,crime,4
baz,fantasy,3
qux,history,2
quux,horror,1
'''
columns = ['name', 'genre', 'rating']
csv = io.StringIO(lines * 6_000_000) # 30M lines

df = pd.read_csv(csv, names=columns, dtype={'rating': 'int8', 'genre': 'category'})

이 경우 로드 시 메모리 사용량을 절반으로 줄입니다.

>>> df.info(memory_usage='deep')
# memory usage: 1.8 GB
>>> pd.read_csv(io.StringIO(lines * 6_000_000)).info(memory_usage='deep')
# memory usage: 3.7 GB

는 빅데이터에서 메모리 오류를 방지하는 한 가지 방법입니다.처음부터 기본 유형의 데이터를 로드할 메모리가 부족할 수 있기 때문에 로드 후 dtype을 변경할 수 있는 것은 아닙니다.

저도 같은 문제인 줄 알았는데, 사실 조금 차이가 있어서 좀 더 쉽게 풀 수 있어요.이 질문을 보고 있는 다른 사용자는 입력 목록의 형식을 확인할 필요가 있습니다.제 경우 처음에는 숫자만 플로트(float)로 되어 있지만 질문에서는 문자열이 아닙니다.

a = [['a', 1.2, 4.2], ['b', 70, 0.03], ['x', 5, 0]]

그러나 데이터 프레임을 만들기 전에 목록을 너무 많이 처리하면 유형이 손실되고 모든 것이 문자열이 됩니다.

numpy 배열을 통한 데이터 프레임 생성

df = pd.DataFrame(np.array(a))

df
Out[5]: 
   0    1     2
0  a  1.2   4.2
1  b   70  0.03
2  x    5     0

df[1].dtype
Out[7]: dtype('O')

는 질문에서와 동일한 데이터 프레임을 제공합니다.여기서 열1과 2의 엔트리는 문자열로 간주됩니다.어쨌든

df = pd.DataFrame(a)

df
Out[10]: 
   0     1     2
0  a   1.2  4.20
1  b  70.0  0.03
2  x   5.0  0.00

df[1].dtype
Out[11]: dtype('float64')

실제로 올바른 형식의 열이 있는 데이터 프레임을 제공합니다.

저도 같은 문제가 있었어요.나는 만족할 만한 해결책을 찾을 수 없었다.저의 해결책은 단순히 이 플로트를 str로 변환하고 '.0'을 제거하는 것이었습니다.

저 같은 경우에는 첫 번째 칸에 붙이고

firstCol = list(df.columns)[0]
df[firstCol] = df[firstCol].fillna('').astype(str).apply(lambda x: x.replace('.0', ''))

그게 누군가에게 도움이 됐으면 좋겠다!

언급URL : https://stackoverflow.com/questions/15891038/change-column-type-in-pandas

반응형