Python 更改熊猫中的列类型
我想将一个表(表示为列表列表)转换为数据帧。作为一个极其简化的示例:Python 更改熊猫中的列类型,python,pandas,dataframe,types,casting,Python,Pandas,Dataframe,Types,Casting,我想将一个表(表示为列表列表)转换为数据帧。作为一个极其简化的示例: a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']] df = pd.DataFrame(a) 将列转换为适当类型的最佳方法是什么,在本例中,将列2和3转换为浮点数?在转换为数据帧时,是否有方法指定类型?还是先创建DataFrame,然后循环遍历列以更改每列的类型更好?理想情况下,我希望以动态方式执行此操作,因为可以有数百列,而我不想确切指定哪些列属于
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a)
将列转换为适当类型的最佳方法是什么,在本例中,将列2和3转换为浮点数?在转换为数据帧时,是否有方法指定类型?还是先创建DataFrame,然后循环遍历列以更改每列的类型更好?理想情况下,我希望以动态方式执行此操作,因为可以有数百列,而我不想确切指定哪些列属于哪种类型。我所能保证的是,每列都包含相同类型的值。这怎么样
a=['a','1.2','4.2'],['b','70','0.03'],['x','5','0']
df=pd.DataFrame(a,列=['1','2','3'])
df
出[16]:
123
0 a 1.2 4.2
1 b 70 0.03
2x50
df.dtypes
出[17]:
一个物体
两个物体
三物体
df[['two','three']=df[['two','three']].astype(float)
df.dtypes
出[19]:
一个物体
两个浮点数64
三个浮点数64
在熊猫中转换类型有四个主要选项:
pd.NA
(熊猫对象表示缺少值)的“最佳可能”数据类型
1. <代码>到数值() 将数据帧的一列或多列转换为数值的最佳方法是使用 此函数将尝试将非数字对象(如字符串)适当地更改为整数或浮点数 基本用法
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
,或者忽略包含这些值的列
下面是一个使用一系列字符串s
的示例,该字符串具有对象数据类型:
>>> 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
与其失败,不如将“pandas”视为缺失/错误的数值。我们可以使用errors
关键字参数将无效值强制为NaN
,如下所示:
>>> pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 4.7
3 NaN
4 10.0
dtype: float64
错误的第三个选项是在遇到无效值时忽略该操作:
>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched
当您希望转换整个数据帧,但不知道哪些列可以可靠地转换为数字类型时,最后一个选项特别有用。在这种情况下,只需写下:
df.apply(pd.to_numeric, errors='ignore')
该函数将应用于数据帧的每一列。可以转换为数字类型的列将被转换,而不能转换的列(例如,它们包含非数字字符串或日期)将被单独保留
向下转型
默认情况下,使用转换为_numeric()
将为您提供int64
或float64
数据类型(或平台固有的任何整数宽度)
这通常是您想要的,但是如果您想节省一些内存并使用更紧凑的数据类型,如float32
或int8
,该怎么办
to_numeric()
提供了向下转换为“整数”、“有符号”、“无符号”、“浮点”的选项。下面是整数类型的简单系列s
的示例:
>>> s = pd.Series([1, 2, -7])
>>> s
0 1
1 2
2 -7
dtype: int64
向下转换为“整数”时,使用可能包含以下值的最小整数:
>>> pd.to_numeric(s, downcast='integer')
0 1
1 2
2 -7
dtype: int8
向下投射到“浮动”类似地拾取比正常浮动类型更小的浮动类型:
>>> pd.to_numeric(s, downcast='float')
0 1.0
1 2.0
2 -7.0
dtype: float32
2. <代码>aType()
该方法使您能够明确表示希望数据帧或序列具有的数据类型。它的用途非常广泛,您可以尝试从一种类型切换到任何其他类型
基本用法
只需选择一种类型:您可以使用NumPy数据类型(例如np.int16
)、一些Python类型(例如bool)或特定类型(例如分类数据类型)
对要转换的对象调用该方法,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”-如果astype()
不知道如何转换序列或数据帧中的值,它将引发错误。例如,如果您有一个NaN
或inf
值,则尝试将其转换为整数时会出现错误
从0.20.0开始,可以通过传递errors='ignore'
来抑制此错误。您的原始对象将原封不动地返回
小心
astype()
功能强大,但有时会“错误地”转换值。例如:
>>> s = pd.Series([1, 2, -7])
>>> s
0 1
1 2
2 -7
dtype: int64
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'])
这些是小整数,那么转换为无符号8位类型以节省内存如何
>>> s.astype(np.uint8)
0 1
1 2
2 249
dtype: uint8
转换成功了,但是-7被包装成249(即28-7)
尝试使用pd.to\u numeric(s,downcast='unsigned')
进行向下转换有助于防止此错误
3. <代码>推断对象() pandas的0.21.0版介绍了转换co的方法
>>> df = df.infer_objects()
>>> df.dtypes
a int64
b object
dtype: object
>>> df.convert_dtypes().dtypes
a Int64
b string
dtype: object
>>> df.convert_dtypes(infer_objects=False).dtypes
a object
b string
dtype: object
# 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'])
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[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')
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'})
a = [['a', 1.2, 4.2], ['b', 70, 0.03], ['x', 5, 0]]
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')
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')
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
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
df.info() gives us initial datatype of temp which is float64
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 date 132 non-null object
1 temp 132 non-null float64
Now, use this code to change the datatype to int64: df['temp'] = df['temp'].astype('int64')
if you do df.info() again, you will see:
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 date 132 non-null object
1 temp 132 non-null int64
this shows you have successfully changed the datatype of column temp. Happy coding!