在Pandas中改变列的数据类型

我想把一个表示为列表的表格转换成Pandas DataFrame。作为一个极其简化的例子。

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

有什么方法可以将列转换为适当的类型,在这种情况下,第2和第3列转换为浮点?是否有办法在转换为DataFrame时指定类型?还是先创建DataFrame,然后通过列循环来改变每一列的类型更好?理想情况下,我希望以动态的方式来做这件事,因为可能有数百个列,我不想确切地指定哪些列是哪种类型。我所能保证的是,每一列都包含相同类型的值。

解决办法

在pandas中,你有三个主要的转换类型的选项。 1.to_numeric() - 提供将非数字类型(如字符串)安全转换为合适的数字类型的功能。(参见 to_datetime()to_timedelta()。) 2.astype() - 将(几乎)任何类型转换为(几乎)任何其他类型(即使这样做不一定明智)。也允许你转换为categorial类型(非常有用)。 3.infer_objects() - 一个实用的方法,如果可能的话,将持有Python对象的对象列转换成pandas类型。 继续阅读,了解这些方法的更详细的解释和用法。

1.`to_numeric()'。

将DataFrame的一个或多个列转换为数值的最好方法是使用pandas.to_numeric()。 这个函数将尝试把非数字对象(如字符串)改为整数或适当的浮点数。

基本用法

to_numeric()的输入是一个系列或一个DataFrame的单列。

>>> 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() "方法,用它来转换一个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关键字参数,允许你强制非数字值为NaN,或简单地忽略包含这些值的列。 下面是一个使用字符串系列s的例子,它的对象是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

我们可能希望'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

errors的第三个选项是,如果遇到无效值,就直接忽略操作。

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

当你想转换整个DataFrame,但不知道哪些列可以可靠地转换为数字类型时,这最后一个选项特别有用。在这种情况下,只需写。

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

该函数将被应用于DataFrame的每一列。可以转换为数字类型的列将被转换,而不能转换的列(例如,它们包含非数字字符串或日期)将被搁置。

下转换

默认情况下,用to_numeric()进行转换会给你一个int64float64的dtype(或你平台上的任何整数宽度)。 这通常是你想要的,但如果你想节省一些内存,使用一个更紧凑的dtype,如float32,或int8呢? to_numeric()让你可以选择下转换为'整数,'有符号','无符号','浮点数'。下面是一个整数类型的简单序列s的例子。

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

下传到'整数&39;时,使用的是可以容纳这些值的最小的整数。

>>> 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().

astype()方法使你能够明确你希望你的DataFrame或Series具有的dtype。它的用途非常广泛,你可以尝试从一种类型转到其他任何类型。

基本用法

选择一个类型:你可以使用NumPy的dtype(比如np.int16),一些Python类型(比如bool),或者pandas的特定类型(比如分类dtype)。 在你想转换的对象上调用该方法,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()不知道如何转换Series或DataFrame中的某个值,它将引发一个错误。例如,如果你有一个 "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')进行降序,可以帮助避免这种错误。

3.infer_objects().

pandas的0.21.0版本引入了方法infer_objects(),用于将具有对象数据类型的DataFrame的列转换为更具体的类型(软转换)。 例如,这里是一个有两列对象类型的DataFrame。一个持有实际的整数,另一个持有代表整数的字符串。

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

使用infer_objects(),你可以将列'a'的类型改为int64。

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

列 'b'已经被忽略了,因为它的值是字符串,而不是整数。如果你想尝试将这两列强制转换为整数类型,你可以使用df.astype(int)来代替。

评论(8)

这个怎么样?

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
评论(10)

这里有一个函数,它的参数是一个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)