-
2021-02-04 08:57:26
使用astype实现dataframe字段类型转换 # -*- coding: UTF-8 -*-
import pandas as pd
df = pd.DataFrame([{'col1':'a', 'col2':'1'}, {'col1':'b', 'col2':'2'}])
print df.dtypes
df['col2'] = df['col2'].astype('int')
print '-----------'
print df.dtypes
df['col2'] = df['col2'].astype('float64')
print '-----------'
print df.dtypes
输出结果: col1 object
col2 object
dtype: object
-----------
col1 object
col2 int32
dtype: object
-----------
col1 object
col2 float64
dtype: object
注:data type list Data type Description
bool_ Boolean (True or False) stored as a byte
int_ Default integer type (same as C long; normally either int64 or int32)
intc Identical to C int (normally int32 or int64)
intp Integer used for indexing (same as C ssize_t; normally either int32 or int64)
int8 Byte (-128 to 127)
int16 Integer (-32768 to 32767)
int32 Integer (-2147483648 to 2147483647)
int64 Integer (-9223372036854775808 to 9223372036854775807)
uint8 Unsigned integer (0 to 255)
uint16 Unsigned integer (0 to 65535)
uint32 Unsigned integer (0 to 4294967295)
uint64 Unsigned integer (0 to 18446744073709551615)
float_ Shorthand for float64.
float16 Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
float32 Single precision float: sign bit, 8 bits exponent, 23 bits mantissa
float64 Double precision float: sign bit, 11 bits exponent, 52 bits mantissa
complex_ Shorthand for complex128.
complex64 Complex number, represented by two 32-bit floats (real and imaginary components)
complex128 Complex number, represented by two 64-bit floats (real and imaginary components)
以上这篇python dataframe astype 字段类型转换方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持聚米学院。
更多相关内容 -
astype()函数
2022-03-01 11:07:561astype()函数可用于转化dateframe某一列的数据类型 如下将dateframe某列的str类型转为int,注意astype()没有replace=True的用法,想要在原数据上修改,要写成如下形式。 注意只有当该列的字符串全是由纯数字构成时...1astype()函数可用于转化dateframe某一列的数据类型
如下将dateframe某列的str类型转为int,注意astype()没有replace=True的用法,想要在原数据上修改,要写成如下形式。
注意只有当该列的字符串全是由纯数字构成时才可以这样写,如果混有字母,会报错:ValueError: invalid literal for int() with base 10:
利用int()函数转字符串也类似
下面是对多个字段的数据类型转换app_train[['uid','index']] = app_train[['uid','index']].astype('int')
isdigit()用于判断一个字符串是否由纯数字构成,如果是返回True,否则False
-
关于numpy的astype(bool)和astype(int)等等
2019-12-04 15:29:57关于numpy的astype(bool)和astype(int)等等 import numpy as np a=[[1,2,1],[2,3,5]] b=[[0,0,0],[2,3,5]] c=np.array(a) d=np.array(b) print(c) print(d) 就是简单的把list列表转化为数组 然后看看加了.as...关于numpy的astype(bool)和astype(int)等等
import numpy as np a=[[1,2,1],[2,3,5]] b=[[0,0,0],[2,3,5]] c=np.array(a) d=np.array(b) print(c) print(d)
就是简单的把list列表转化为数组
然后看看加了.astype(bool)是什么意思?
正如astype的中文意思,作为布尔类型,也就是true or false
代码如下import numpy as np a=[[1,2,1],[2,3,5]] b=[[0,0,0],[2,3,5]] c=np.array(a).astype(bool) d=np.array(b).astype(bool) print(c) print(d)
再看看结果
这下明白了吗?0代表False 非0代表True!
那么.astype(int)是啥意思呢?
那不就是转化为整型数据吗!True和False转化为整型数据是什么样子呢?
不就是0和1嘛!
代码如下:import numpy as np a=[[1,2,1],[2,3,5]] b=[[0,0,0],[2,3,5]] c=np.array(a).astype(bool).astype(int) d=np.array(b).astype(bool).astype(int) print(c) print(d)
看一下,是这样的吧!
那么astype(float)呢?是什么意思?不用我说你也知道了吧,那不明白看下面代码!import numpy as np a=[[1,2,1],[2,3,5]] b=[[0,0,0],[2,3,5]] c=np.array(a).astype(bool).astype(int).astype(float) d=np.array(b).astype(bool).astype(int).astype(float) print(c) print(d)
希望可以帮助你 -
[Pandas] 类型转换astype()
2022-02-14 11:52:57[Pandas] 类型转换astype()astype()是最常见也是最通用的数据类型转换方法
import pandas as pd df = pd.DataFrame([['liver','E',89,21,24,64], ['Arry','C',36,37,37,57], ['Ack','A',57,60,18,84], ['Eorge','C',93,96,71,78], ['Oah','D',65,49,61,86] ], columns = ['name','team','Q1','Q2','Q3','Q4']) res = df.dtypes df.Q1.astype('int32').dtypes # dtype('int32') df.astype({'Q1':'int32','Q2':'int32'}).dtypes
结果展示
df
res
扩展
# 以下是一些使用示例: df.index.astype('int64') # 索引类型转换 df.astype('int32') # 所有数据转换为int32 df.astype({'col1':'int32'}) # 指定字段转指定类型 s.astype('int64') s.astype('int64',copy = False) # 不与原数据关联 df['name'].astype('object') data['Q4'].astype('float') s.astype('datatime64[ns]') # 转为时间类型 data['状态'].astype('bool')
数据类型
df.dtypes会返回每个字段的数据类型及DataFrame整体的类型
如果是Series,需要用s.dtype
import pandas as pd df = pd.DataFrame([['liver','E',89,21,24,64], ['Arry','C',36,37,37,57], ['Ack','A',57,60,18,84], ['Eorge','C',93,96,71,78], ['Oah','D',65,49,61,86] ], columns = ['name','team','Q1','Q2','Q3','Q4']) df.dtypes s = pd.Series(['One','Two','Three']) s.dtype
结果展示
df
s
当数据的格式不具备转换为目标类型的条件时,需要先对数据进行处理
例如“89.3%”是一个字符串,要转换为数字,要先去掉百分号:
# 将"89.3%"这样的文本转为浮点数 data.rate.apply(lambda x:x.replace('%','')).astype('float')/100
加载数据时可以指定数据各列的类型:
import pandas as pd # 对所有字段指定统一类型 df = pd.DataFrame(data, dtype = 'float32') # 对每个字段分别指定 df = pd.read_excel(data, dtype = {'team':'string','Q1':'int32'})
-
浅谈python 中的 type(), dtype(), astype()的区别
2021-01-29 03:39:371)由于 list、dict 等可以包含不同的数据类型,因此不可调用dtype()函数2)np.array 中要求所有元素属于同一数据类型,因此可调用dtype()函数astype()改变np.array中所有数据元素的数据类型。备注... -
python里的astype是什么意思?
2020-11-29 09:46:33展开全部astype是实现2113变量类型转换,例如astype(type): returns a copy of the array converted to the specified type.a =a.astype('Float64')b = b.astype('Int32')Python中与数据5261类型4102相关函数及属性... -
pandas 转换类型函数astype()
2022-02-16 14:25:32pandas astype()将数据转换为指定的数据类型(可多列操作) 功能: 将pandas series转换为指定的dtype 可转换类型: 1.float 2.int 3.bool 4.datetime64[ns] 5.datetime[ns, tz] 6.timedelta[ns] 7.category 8.object ... -
python-DataFrame.astype()错误参数
2020-12-11 04:20:06使用列的字典时,astype引发ValueError.我试图将大DF中的稀疏列的类型转换(从float到int).我的问题是NaN值.即使将errors参数设置为’ignore’,使用列的字典时也不会忽略它们.这是一个玩具示例:t=pd.DataFrame([[1.01... -
Python astype(np.float)函数使用方法解析
2021-01-14 03:27:05我的数据库如图结构我取了其中的name age nr,做成array,只要...那么问题来了,取出的数据代入公式进行计算的时候,就会类型不符,这是就用到astype(np.float)代码如下import pymysqlimport numpy as npconn = pymy... -
Numpy:astype(bool) 和 astype(int)
2020-06-05 21:36:121 np.array() 将输入转换成数组。 栗子: import numpy as np a=[[1,2,1],[2,3,5]] b=[[0,0,0],[2,3,5]] c=np.array(a) d=np.array(b) ...正如astype的中文意思,作为布尔类型,也就是true or . -
np.astype uint8之后发生了什么
2021-10-26 10:55:11b = np.arange(10).astype('float32') c = -b b[9] = 0.7 print('b',b) print('c',c) print(b.astype('uint8')) print(c.astype('uint8')) 输出 b [0. 1. 2. 3. 4. 5. 6. 7. 8. 0.7] c [-0. -1. -2. -3. -4. -5. -... -
AttributeError: ‘NoneType‘ object has no attribute ‘astype
2022-03-30 21:19:15今天在复现faster RCNN网络时,出现AttributeError: 'NoneType' object has no attribute 'astype'报错,如下图所示 通过dug,发现im的shape为none,究其原因是因为cv.imread无法读取图像,主要原因是因为我数据集中... -
‘NoneType‘ object has no attribute ‘astype‘问题
2021-11-29 09:53:47image = cv2.imread(r'D:\pycharmfile\Data\uav1 - 副本\c-testing\frames\01\060.jpg', cv2.IMREAD_COLOR).astype(np.float32) / 255.0 这一行代码报错 查了好几个方法,有方法说是图片后缀改成.jpg但是实际上... -
数据格式汇总及type, astype, dtype区别
2018-01-01 16:28:56三、看看数据转换 astype等知识 1、向下取整 2、四舍五入 3、向上取整 4、分别取整数部分和小数部分 - 接下来是重点,astype 转载和疑问声明 我祝各位帅哥,和美女,你们永远十八岁,嗨嘿嘿~~~ uint8:在此输入正文... -
numpy.astype数据精度导致数据变化的问题
2019-07-23 18:43:48在用numpy.astype强制转换数据类型的时候,由于numpy精度的问题将会对长度超过16位的数据发生不可预见的变化。 见以下样例: a=np.random.randint(10000000000000000,100000000000000000,6,dtype=np.int64).... -
Pandas数据类型转换df.astype()、数据类型查看df.dtypes
2021-06-10 11:24:21数据类型转换.astype: df.index.astype('int64') # 索引类型转换 df.astype('int64') # 所有数据转换为 int64 df.astype('int64', copy=False) # 不与原数据关联 td_link_data.astype({'管理域': 'int32'}) # 指定... -
numpy的astype函数
2020-06-30 18:42:34astype函数用于array中数值类型转换 x = np.array([1, 2, 2.5]) x.astype(int)1... -
数据预处理:pandas类型转化astype
2020-07-09 17:52:16astype基本也就是两种用作,数字转化为单纯字符串,单纯数字的字符串转化为数字,含有其他的非数字的字符串是不能通过astype进行转化的。 需要引入其他的方法进行转化,也就有了下面的自定义函数方法 自定义函数... -
解决AttributeError: ‘NoneType‘ object has no attribute ‘astype
2021-03-20 22:43:44image = cv2.imread(‘train/2.jpg’, cv2.IMREAD_COLOR).astype(np.float32) / 255.0 # 颜色空间转换 BGR转为HLS hlsImg = cv2.cvtColor(image, cv2.COLOR_BGR2HLS) #然后我们需要做两个滑动块,一个调节亮度,一个... -
问题解决之 AttributeError: ‘NoneType‘ object has no attribute ‘astype
2022-02-11 19:06:13运行代码时,出现报错 AttributeError: 'NoneType' object has no attribute 'astype',具体信息如下图所示: Traceback (most recent call last): File "work/person_search-master/tools/demo.py", line 82, in &... -
python强制类型转换astype
2019-01-08 11:56:30在进行将多个表的数据合并到一个表后,发现输出到...找了一些解决方法,发现用.astype('数据类型')还是挺方便的。我在输出时,将数值型的数据(int)转化成了字符串(str)。 使用方法: df.astype('数据类型') ... -
Python更改数据类型——astype()方法和to_numeric()函数
2020-11-19 17:26:28文章目录明确指定数据的类型通过dtypes属性进行查看创建Pandas对象指定数据类型转换数据类型通过astype()方法强制转换数据的类型 明确指定数据的类型 通过dtypes属性进行查看 import pandas as pd df = pd.... -
np.astype()
2019-07-01 20:09:421.作用:就是转换numpy数组的数据类型 举个例子 arr = np.arange((10)) print(arr, arr.dtype, sep="\n") =================================== [0 1 2 3 4 5 6 7 8 9] int32 #可以看到,他的...arr = arr.astype("f... -
Python-辨析type/dtype/astype用法
2018-11-07 20:43:21Python中与数据类型相关函数及属性有如下三个:type/dtype/astype。 名称 描述 type() 返回参数的数据类型 dtype 返回数组中元素的数据类型 astype() 对数据类型进行转换 type()用于获取数据类型 #... -
numpy()的类型-astype、dtype
2020-04-06 16:52:52查到一共有四个方法对于numpy数组:ndim、shape 、astype 、 dtype ndim返回的是一个数,表示的是数组的维度;shape返回的是数组的size,dtype返回的是数组中值的类型;astype是强制类型转换:可以转换为 float64、... -
深入浅出之dtype( )和astype( )函数
2018-12-25 11:34:16NumPy最重要的一个特点就是其N维数组对象(即ndarray),该对象是一个快速而灵活的大数据集容器。你可以利用这种数组对整块数据执行一些数学运算,...3. astype( )函数 作用:转换数据类型dtype -
numpy astype方法
2022-02-25 12:59:39astype方法 a.astype(np.int)