更改Pandas中列的数据类型

688 python types casting dataframe pandas

我想将表格(表示为列表列表)转换为Pandas DataFrame.作为一个极其简化的例子:

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

将列转换为适当类型的最佳方法是什么,在这种情况下,将第2列和第3列转换为浮点数?有没有办法在转换为DataFrame时指定类型?或者最好先创建DataFrame,然后循环遍历列以更改每列的类型?理想情况下,我想以动态方式执行此操作,因为可能有数百列,我不想确切地指定哪些列属于哪种类型.我可以保证的是,每列包含相同类型的值.

Ale*_*ley 967

您有三个主要选项来转换pandas中的类型.


1. to_numeric()

将DataFrame的一个或多个列转换为数值的最佳方法是使用to_datetime().

此函数将尝试根据需要将非数字对象(如字符串)更改为整数或浮点数.

基本用法

输入to_timedelta()是DataFrame的Series或单列.

>>> 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
Run Code Online (Sandbox Code Playgroud)

如您所见,返回一个新系列.请记住将此输出分配给变量或列名称以继续使用它:

# convert Series
my_series = pd.to_numeric(my_series)

# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])
Run Code Online (Sandbox Code Playgroud)

您还可以使用它通过以下astype()方法转换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)
Run Code Online (Sandbox Code Playgroud)

只要你的价值都可以转换,那可能就是你所需要的.

错误处理

但是,如果某些值无法转换为数字类型呢?

infer_objects()还有一个to_numeric()关键字参数,允许您强制使用非数字值pandas.to_numeric(),或者只是忽略包含这些值的列.

这是一个使用一系列to_numeric()具有对象dtype 的字符串的示例:

>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0         1
1         2
2       4.7
3    pandas
4        10
dtype: object
Run Code Online (Sandbox Code Playgroud)

如果无法转换值,则默认行为是提升.在这种情况下,它无法处理字符串'pandas':

>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string
Run Code Online (Sandbox Code Playgroud)

我们可能希望将"熊猫"视为缺失/错误的数值,而不是失败.我们可以apply()使用to_numeric()关键字参数强制将无效值强制如下:

>>> pd.to_numeric(s, errors='coerce')
0     1.0
1     2.0
2     4.7
3     NaN
4    10.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)

第三个选项errors是在遇到无效值时忽略该操作:

>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched
Run Code Online (Sandbox Code Playgroud)

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

df.apply(pd.to_numeric, errors='ignore')
Run Code Online (Sandbox Code Playgroud)

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

溯造型

默认情况下,转换NaN将为您提供a sNaNdtype(或者您的平台本机的任何整数宽度).

这通常是你想要的,但如果你想节省一些内存并使用更紧凑的dtype,比如errors,或者errors怎么办?

to_numeric()为您提供向下转换为'整数','签名','无符号','浮动'的选项.这是一个简单int64的整数类型的例子:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64
Run Code Online (Sandbox Code Playgroud)

向下转换为'整数'使用可以保存值的最小整数:

>>> pd.to_numeric(s, downcast='integer')
0    1
1    2
2   -7
dtype: int8
Run Code Online (Sandbox Code Playgroud)

向下'浮动'同样选择一个小于正常的浮动类型:

>>> pd.to_numeric(s, downcast='float')
0    1.0
1    2.0
2   -7.0
dtype: float32
Run Code Online (Sandbox Code Playgroud)

2. float64

通过该float32方法,您可以明确了解您希望DataFrame或Series具有的dtype.它非常通用,你可以尝试从一种类型转向另一种类型.

基本用法

只需选择一种类型:您可以使用NumPy dtype(例如int8),某些Python类型(例如bool)或pandas特定类型(例如分类dtype).

在要转换的对象上调用该方法,并to_numeric()尝试为您转换它:

# 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')
Run Code Online (Sandbox Code Playgroud)

注意我说"尝试" - 如果s不知道如何转换Series或DataFrame中的值,则会引发错误.例如,如果您有一个astype()astype()值,则在尝试将其转换为整数时会出错.

从pandas 0.20.0开始,可以通过传递来抑制此错误np.int16.您的原始对象将不会被返回.

小心

astype()功能强大,但它有时会"错误地"转换值.例如:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64
Run Code Online (Sandbox Code Playgroud)

这些是小整数,那么如何转换为无符号8位类型以节省内存?

>>> s.astype(np.uint8)
0      1
1      2
2    249
dtype: uint8
Run Code Online (Sandbox Code Playgroud)

转换工作,但-7被包围成249(即2 8 - 7)!

尝试向下转换astype()可能有助于防止此错误.


3. NaN

Pandas版本0.21.0引入了inf将具有对象数据类型的DataFrame列转换为更具体类型(软转换)的方法.

例如,这是一个具有两列对象类型的DataFrame.一个包含实际整数,另一个包含表示整数的字符串:

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

使用errors='ignore',您可以将列'a'的类型更改为int64:

>>> df = df.infer_objects()
>>> df.dtypes
a     int64
b    object
dtype: object
Run Code Online (Sandbox Code Playgroud)

列'b'一直保留,因为它的值是字符串,而不是整数.如果您想尝试强制将两列转换为整数类型,则可以使用astype().

  • `.convert_objects`从`0.17`开始被删除 - 用'df.to_numeric`代替 (11认同)
  • 此外,与.astype(float)不同,这会将字符串转换为NaN而不是引发错误 (7认同)
  • 谢谢 - 我应该更新这个答案.值得注意的是,`pd.to_numeric`及其伴随方法一次只能在一列上工作,与`convert_objects`不同.关于API中替换功能的讨论似乎是[正在进行](https://github.com/pydata/pandas/issues/11221); 我希望一个适用于整个DataFrame的方法将保留,因为它非常有用. (4认同)
  • @RoyalTS:最好使用`astype`(如在另一个答案中),即`.astype(numpy.int32)`. (4认同)

her*_*ara 434

这个怎么样?

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
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的方法,但是当列中有NaN时它不起作用.不知道为什么NaN在将float转换为int时不能保留NaN:`ValueError:无法将NA转换为整数` (18认同)
  • 当我按照建议尝试时,我收到警告`SettingWithCopyWarning:尝试在DataFrame的切片副本上设置一个值.尝试使用.loc [row_index,col_indexer] = value.这可能是在较新版本的熊猫中引入的,我没有看到任何错误,但我只是想知道这个警告是什么.任何的想法? (16认同)
  • 是! `pd.DataFrame`有一个'dtype`参数,可能会让你找到你正在寻找的东西.df = pd.DataFrame(a,columns = ['one','two','three'],dtype = float)在[2]中:df.dtypes Out [2]:一个对象两个float64三个float64 dtype:object (9认同)
  • @GillBates是的,在字典中.`DF = pd.DataFrame(一,列= [ '一个', '2', '3'],D型细胞= { '一':STR, '二':整数, '三':浮子})`.我很难找到接受的"dtype"值的规范.列表会很好(目前我做`dict(enumerate(my_list))`). (6认同)
  • 这可以在创建数据帧时完成吗? (4认同)
  • @orange 警告是提醒用户注意链式操作的潜在混淆行为,以及熊猫返回数据帧的副本而不是编辑数据帧。请参阅 http://stackoverflow.com/questions/20625582/how-to-deal-with-this-pandas-warning 和相关内容。 (2认同)

小智 36

以下代码将更改列的数据类型.

df[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')
Run Code Online (Sandbox Code Playgroud)

代替数据类型,你可以给你的数据类型.你想要什么像str,float,int等.

  • 请注意,当使用 data_type ``bool``` 将其应用于包含字符串 ``` 'True' ``` 和 ``` 'False' ``` 的列时,所有内容都会更改为 ```True ``。 (2认同)

Raj*_*man 21

df = df.astype({"columnname": str})
Run Code Online (Sandbox Code Playgroud)

#eg - 用于将列类型更改为字符串 #df 是您的数据框


Har*_*ens 15

这是一个函数,它将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')
Run Code Online (Sandbox Code Playgroud)

所以,举个例子:

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'])
Run Code Online (Sandbox Code Playgroud)


cs9*_*s95 14

熊猫 >= 1.0

下面的图表总结了 Pandas 中一些最重要的转换。

在此处输入图片说明

转换为字符串是微不足道的.astype(str),图中未显示。

“硬”与“软”转换

请注意,此上下文中的“转换”可以指将文本数据转换为其实际数据类型(硬转换),或为对象列中的数据推断更合适的数据类型(软转换)。为了说明差异,请看

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                                                     
Run Code Online (Sandbox Code Playgroud)


cot*_*ail 11

1. 将长浮点数的字符串表示形式转换为数值

\n

如果列包含需要精确计算的长浮点数的字符串表示形式(float将在 15 位数字后四舍五入,pd.to_numeric甚至更不精确),则从Decimal内置decimal库中使用。列的 dtype 将object支持decimal.Decimal所有算术运算,因此您仍然可以执行矢量化运算,例如算术和比较运算符等。

\n
from decimal import Decimal\ndf = pd.DataFrame({\'long_float\': ["0.1234567890123456789", "0.123456789012345678", "0.1234567890123456781"]})\n\ndf[\'w_float\'] = df[\'long_float\'].astype(float)       # imprecise\ndf[\'w_Decimal\'] = df[\'long_float\'].map(Decimal)      # precise\n
Run Code Online (Sandbox Code Playgroud)\n

资源

\n

在上面的例子中,float将它们全部转换为相同的数字,同时Decimal保持它们的差异:

\n
df[\'w_Decimal\'] == Decimal(df.loc[1, \'long_float\'])   # False, True, False\ndf[\'w_float\'] == float(df.loc[1, \'long_float\'])       # True, True, True\n
Run Code Online (Sandbox Code Playgroud)\n

2. 将长整数的字符串表示形式转换为整数

\n

默认情况下,astype(int)转换为,如果数字特别长(例如电话号码),则int32转换为 ( ) ;OverflowError尝试\'int64\'(甚至float)代替:

\n
df[\'long_num\'] = df[\'long_num\'].astype(\'int64\')\n
Run Code Online (Sandbox Code Playgroud)\n

顺便说一句,如果您得到SettingWithCopyWarning,则打开写入时复制模式(有关更多信息,请参阅此答案)并再次执行您正在执行的操作。例如,如果您要将col1和转换col2为 float 数据类型,则执行以下操作:

\n
pd.set_option(\'mode.copy_on_write\', True)\ndf[[\'col1\', \'col2\']] = df[[\'col1\', \'col2\']].astype(float)\n\n# or use assign to overwrite the old columns and make a new copy\ndf = df.assign(**df[[\'col1\', \'col2\']].astype(float))\n
Run Code Online (Sandbox Code Playgroud)\n

3. 将整数转换为timedelta

\n

另外,长字符串/整数可能是 datetime 或 timedelta,在这种情况下,使用to_datetimeto_timedelta转换为 datetime/timedelta dtype:

\n
df = pd.DataFrame({\'long_int\': [\'1018880886000000000\', \'1590305014000000000\', \'1101470895000000000\', \'1586646272000000000\', \'1460958607000000000\']})\ndf[\'datetime\'] = pd.to_datetime(df[\'long_int\'].astype(\'int64\'))\n# or\ndf[\'datetime\'] = pd.to_datetime(df[\'long_int\'].astype(float))\n\ndf[\'timedelta\'] = pd.to_timedelta(df[\'long_int\'].astype(\'int64\'))\n
Run Code Online (Sandbox Code Playgroud)\n

资源1

\n

4. 将 timedelta 转换为数字

\n

要执行相反的操作(将 datetime/timedelta 转换为数字),请将其视为\'int64\'. 如果您正在构建一个需要以某种方式包含时间(或日期时间)作为数值的机器学习模型,这可能会很有用。只需确保如果原始数据是字符串,则在转换为数字之前必须将它们转换为 timedelta 或 datetime。

\n
df = pd.DataFrame({\'Time diff\': [\'2 days 4:00:00\', \'3 days\', \'4 days\', \'5 days\', \'6 days\']})\ndf[\'Time diff in nanoseconds\'] = pd.to_timedelta(df[\'Time diff\']).view(\'int64\')\ndf[\'Time diff in seconds\'] = pd.to_timedelta(df[\'Time diff\']).view(\'int64\') // 10**9\ndf[\'Time diff in hours\'] = pd.to_timedelta(df[\'Time diff\']).view(\'int64\') // (3600*10**9)\n
Run Code Online (Sandbox Code Playgroud)\n

资源3

\n

5. 将日期时间转换为数字

\n

对于日期时间,日期时间的数字视图是该日期时间与 UNIX 纪元 (1970-01-01) 之间的时间差。

\n
df = pd.DataFrame({\'Date\': [\'2002-04-15\', \'2020-05-24\', \'2004-11-26\', \'2020-04-11\', \'2016-04-18\']})\ndf[\'Time_since_unix_epoch\'] = pd.to_datetime(df[\'Date\'], format=\'%Y-%m-%d\').view(\'int64\')\n
Run Code Online (Sandbox Code Playgroud)\n

资源4

\n

6.astypeto_numeric

\n
df = pd.DataFrame(np.random.default_rng().choice(1000, size=(10000, 50)).astype(str))\ndf = pd.concat([df, pd.DataFrame(np.random.rand(10000, 50).astype(str), columns=range(50, 100))], axis=1)\n\n%timeit df.astype(dict.fromkeys(df.columns[:50], int) | dict.fromkeys(df.columns[50:], float))\n# 488 ms \xc2\xb1 28 ms per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\n%timeit df.apply(pd.to_numeric)\n# 686 ms \xc2\xb1 45.8 ms per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n
Run Code Online (Sandbox Code Playgroud)\n


Tho*_*ves 10

当我只需要指定特定的列并且想要明确时,我就使用了(每个DOCS LOCATION):

dataframe = dataframe.astype({'col_name_1':'int','col_name_2':'float64', etc. ...})
Run Code Online (Sandbox Code Playgroud)

因此,使用原始问题,但为其提供列名称...

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'})
Run Code Online (Sandbox Code Playgroud)


Bab*_*pha 8

df.info() 为我们提供了 temp 的初始数据类型,即 float64

 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   date    132 non-null    object 
 1   temp    132 non-null    float64
Run Code Online (Sandbox Code Playgroud)

现在,使用以下代码将数据类型更改为 int64:

df['temp'] = df['temp'].astype('int64')
Run Code Online (Sandbox Code Playgroud)

如果你再次执行 df.info(),你将看到:

  #   Column  Non-Null Count  Dtype 
 ---  ------  --------------  ----- 
  0   date    132 non-null    object
  1   temp    132 non-null    int64 
Run Code Online (Sandbox Code Playgroud)

这表明您已成功更改了 temp 列的数据类型。快乐编码!


Mik*_*eyE 6

如何创建两个数据框,每个数据框的列都有不同的数据类型,然后将它们一起添加?

d1 = pd.DataFrame(columns=[ 'float_column' ], dtype=float)
d1 = d1.append(pd.DataFrame(columns=[ 'string_column' ], dtype=str))
Run Code Online (Sandbox Code Playgroud)

结果

In[8}:  d1.dtypes
Out[8]: 
float_column     float64
string_column     object
dtype: object
Run Code Online (Sandbox Code Playgroud)

创建数据框后,可以使用第1列中的浮点变量和第2列中的字符串(或所需的任何数据类型)填充它.


小智 5

从 pandas 1.0.0 开始,我们有pandas.DataFrame.convert_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
Run Code Online (Sandbox Code Playgroud)