我从列表列表创建了一个数据帧:
table = [
['a', '1.2', '4.2' ],
['b', '70', '0.03'],
['x', '5', '0' ],
]
df = pd.DataFrame(table)
如何将列转换为特定类型?在这种情况下,我想将第 2 列和第 3 列转换为浮点数。
有没有办法在转换为数据帧时指定类型?还是先创建数据帧,然后循环访问列以更改每列的类型更好?理想情况下,我想以动态方式执行此操作,因为可能有数百列,并且我不想确切指定哪些列属于哪种类型。我只能保证每列都包含相同类型的值。
网友回答:
使用这个:
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,float,int等。
网友回答:
在熊猫中转换类型有四个主要选项:
to_numeric()
– 提供将非数字类型(例如字符串)安全地转换为合适的数字类型的功能。(另请参阅和。to_datetime()
to_timedelta()
astype()
– 将(几乎)任何类型的转换为(几乎)任何其他类型的(即使这样做不一定明智)。还允许您转换为分类类型(非常有用)。infer_objects()
– 一种实用程序方法,用于将包含 Python 对象的对象列转换为 pandas 类型(如果可能)。convert_dtypes()
– 将数据帧列转换为支持(熊猫的对象指示缺失值)的“最佳可能”dtype。pd.NA
请继续阅读,了解每种方法的更详细说明和用法。
to_numeric()
将数据帧的一个或多个列转换为数值的最佳方法是使用 。pandas.to_numeric()
此函数将尝试根据需要将非数字对象(如字符串)更改为整数或浮点数。
的输入是数据帧的系列或单个列。to_numeric()
>>> 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"])
您还可以使用它通过以下方法转换数据帧的多个列:apply()
# 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
NaN
下面是使用具有对象 dtype 的一系列字符串的示例:s
>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0 1
1 2
2 4.7
3 pandas
4 10
dtype: object
默认行为是在无法转换值时引发。在这种情况下,它无法处理字符串“熊猫”:
>>> 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
最后一个选项对于转换整个数据帧特别有用,但不知道我们的哪些列可以可靠地转换为数字类型。在这种情况下,只需写:
df.apply(pd.to_numeric, errors='ignore')
该函数将应用于数据帧的每一列。可以转换为数字类型的列将被转换,而不能转换为数字类型的列(例如,它们包含非数字字符串或日期)将被单独保留。
默认情况下,转换 with 将为您提供 或 dtype(或您的平台原生的任何整数宽度)。to_numeric()
int64
float64
这通常是您想要的,但是如果您想节省一些内存并使用更紧凑的 dtype(如 、 或 ?float32
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
astype()
该方法使您能够明确表示希望数据帧或系列具有的 dtype。它非常通用,因为您可以尝试从一种类型转到任何其他类型。astype()
只需选择一个类型:您可以使用 NumPy dtype(例如)、一些 Python 类型(例如 bool)或特定于 pandas 的类型(例如分类 dtype)。np.int16
在要转换的对象上调用该方法,并尝试为您转换它:astype()
# 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”——如果不知道如何转换系列或数据帧中的值,它将引发错误。例如,如果你有一个 or 值,则在尝试将其转换为整数时会收到错误。astype()
NaN
inf
从 pandas 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(即 28 – 7)!
尝试向下转换使用代替可以帮助防止此错误。pd.to_numeric(s, downcast='unsigned')
infer_objects()
pandas 的 0.21.0 版引入了将具有对象数据类型的数据帧列转换为更具体类型(软转换)的方法。infer_objects()
例如,下面是一个包含两列对象类型的数据帧。一个保存实际整数,另一个保存表示整数的字符串:
>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a object
b object
dtype: object
使用 ,您可以将列 ‘a’ 的类型更改为 int64:infer_objects()
>>> df = df.infer_objects()
>>> df.dtypes
a int64
b object
dtype: object
列 ‘b’ 一直被保留,因为它的值是字符串,而不是整数。如果要强制将两列都强制为整数类型,可以改用。df.astype(int)
convert_dtypes()
版本 1.0 及更高版本包括将系列和数据帧列转换为支持缺失值的最佳 dtype 的方法。convert_dtypes()
pd.NA
这里的“最佳可能”是指最适合保存值的类型。比如这个 pandas 整数类型,如果所有值都是整数(或缺失值):Python 整数对象的对象列被转换为,一列 NumPy 值,就会变成 pandas dtype。Int64
int32
Int32
使用我们的 数据帧 ,我们得到以下结果:object
df
>>> df.convert_dtypes().dtypes
a Int64
b string
dtype: object
由于列“a”保存整数值,因此将其转换为类型(与 不同,它能够保存缺失值)。Int64
int64
列 ‘b’ 包含字符串对象,因此更改为 pandas’ dtype。string
默认情况下,此方法将从每列中的对象值推断类型。我们可以通过以下方式更改它:infer_objects=False
>>> df.convert_dtypes(infer_objects=False).dtypes
a object
b string
dtype: object
现在列“a”仍然是一个对象列:熊猫知道它可以被描述为一个“整数”列(内部它运行),但没有确切地推断出它应该具有的整数dtype,所以没有转换它。列“b”再次转换为“字符串”dtype,因为它被识别为包含“字符串”值。infer_dtype
模板简介:该模板名称为【有没有办法在转换为数据帧时指定类型?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。