Hàm DataFrame.astype () được sử dụng để ép kiểu dữ liệu cột (dtype) trong đối tượng gấu trúc, nó hỗ trợ String, flat, date, int, datetime bất kỳ kiểu dữ liệu nào khác được Numpy hỗ trợ. Điều này rất hữu ích khi bạn muốn truyền cột DataFrame từ kiểu dữ liệu này sang kiểu dữ liệu khác. Show Nội dung chính ShowShow
pandas astype () Các điểm chính –
1. Cú pháp DataFrame.astype ()2. DataFrame.astype () – Truyền Tất cả các Cột Kiểu dữ liệu (dtype)DataFrame.astype(). Chức năng này có dtype, copyvà errors params. # astype() Syntax DataFrame.astype(dtype, copy=True, errors="raise") 3. Thay đổi loại cột cụ thểastype().
2. DataFrame.astype () – Truyền Tất cả các Cột Kiểu dữ liệu (dtype)3. Thay đổi loại cột cụ thểastype() cố gắng truyền tất cả các cột DataFrame thành được chỉ định numpy.dtype hoặc các kiểu Python (int, string, float, date, datetime). Nếu bất kỳ cột nào không thể truyền do dữ liệu hoặc nanô không hợp lệ, điều đó sẽ gây ra lỗi ‘ValueError: chữ không hợp lệ’ và không hoạt động. 4. astype () – Truyền nhiều cột bằng cách sử dụng Dict import pandas as pd import numpy as np # Create DataFrame from Dictionary technologies = { 'Fee' :["20000","25000","26000"], 'Discount':["1000","2300","1500"] } df = pd.DataFrame(technologies) print(df.dtypes) # Outputs Fee object Discount object dtype: object 5. astype () với lỗi tăng hoặc bỏ qua Sự kết luậnSố nguyên có dấu 64 bitbạn có thể dùng numpy.int64,numpy.int_, int64 hoặc int như tham số. Để truyền tới Số nguyên có dấu 32 bitsử dụng numpy.int32, int32. # Cast all columns to int df = df.astype(np.int64) df = df.astype('int64') df = df.astype('int') print(df.dtypes) # All gives the same output. Fee int64 Discount int64 dtype: object Người giới thiệu pandas astype () Các điểm chính –numpy.str_ hoặc string. # Cast all columns to string df = df.astype('string') print(df.dtypes) # Outputs Fee string Discount string dtype: object Nó được sử dụng để ép kiểu dữ liệu (dtype).numpy.float64, numpy.float_, float # Cast all columns to float df = df.astype('float') print(df.dtypes) # Outputs Fee float Discount flat dtype: object 3. Thay đổi loại cột cụ thể4. astype () – Truyền nhiều cột bằng cách sử dụng DictSeries.astype()vì mỗi cột trên DataFrame là Chuỗi gấu trúc, tôi sẽ lấy cột từ DataFrame làm Chuỗi và sử dụng astype(). Trong ví dụ dưới đây df.Fee hoặc df[‘Fee’] trả về đối tượng Dòng. # Cast specific column type df.Fee = df.Fee.astype('int') (or) df.Fee = df['Fee'].astype('int') print(df.dtypes) # Outputs Fee int64 Discount object dtype: object 4. astype () – Truyền nhiều cột bằng cách sử dụng Dict5. astype () với lỗi tăng hoặc bỏ qua tham số của astype() cũng hỗ trợ Từ điển ở định dạng {col: dtype,…} trong đó col là nhãn cột và dtype là numpy.dtype hoặc kiểu Python (int, string, float, date, datetime) để ép một hoặc nhiều cột DataFrame. import pandas as pd import numpy as np # Create DataFrame from Dictionary technologies = { 'Courses':["Spark","PySpark","Hadoop"], 'Fee' :["20000","25000","26000"], 'Duration':['30day','40days','35days'], 'Discount':["1000","2300","1500"] } df = pd.DataFrame(technologies) print(df.dtypes) # Outputs Courses object Fee object Duration object Discount object dtype: object Sự kết luậnDataFrame.astype()đúc Courses đến string, Fee đến int và Discount đến float. df2 = df.astype({'Courses':'string','Fee':'int','Discount':'float'}) print(df2.dtypes) # Outputs Courses string Fee int64 Duration object Discount float64 dtype: object 5. astype () với lỗi tăng hoặc bỏ quaSự kết luậnerrors tham số. Theo mặc định, nó sử dụng raise như một giá trị có nghĩa là tạo ra một ngoại lệ khi không thể truyền do dữ liệu không hợp lệ cho kiểu. Người giới thiệuCourses có string dữ liệu, hãy truyền dữ liệu này tới int và hãy xem chuyện gì xảy ra. # Raise error when unable to cast df.Courses = df.Courses.astype('int') # Outputs ValueError: invalid literal for int() with base 10: 'Spark' pandas astype () Các điểm chính – # Ignore error when unable to cast df.Courses = df.Courses.astype('int', errors="ignore") print(df.dtypes) # Outputs Courses string Fee int64 Duration object Discount float64 dtype: object Sự kết luậnNgười giới thiệu Người giới thiệu |