更改熊猫中的列类型

2024-11-19 08:38:00
admin
原创
186
摘要:问题描述:我从列表列表中创建了一个 DataFrame:table = [ ['a', '1.2', '4.2' ], ['b', '70', '0.03'], ['x', '5', '0' ], ] df = pd.DataFrame(table) 如何将列转...

问题描述:

我从列表列表中创建了一个 DataFrame:

table = [
    ['a',  '1.2',  '4.2' ],
    ['b',  '70',   '0.03'],
    ['x',  '5',    '0'   ],
]

df = pd.DataFrame(table)

如何将列转换为特定类型?在本例中,我想将第 2 列和第 3 列转换为浮点数。

有没有办法在将列表转换为 DataFrame 时指定类型?还是先创建 DataFrame,然后循环遍历列以更改每列的 dtype?理想情况下,我希望以动态方式执行此操作,因为可能有数百列,并且我不想准确指定哪些列属于哪种类型。我只能保证每列都包含相同类型的值。


解决方案 1:

在 Pandas 中,转换类型主要有四种方式:

  1. to_numeric()- 提供将非数字类型(例如字符串)安全地转换为合适的数字类型的功能。(另请参阅to_datetime()to_timedelta()。)

  2. astype()- 将(几乎)任何类型转换为(几乎)任何其他类型(即使这样做不一定明智)。还允许您转换为分类类型(非常有用)。

  3. infer_objects()- 一种实用方法,用于将包含 Python 对象的对象列转换为 pandas 类型(如果可能)。

  4. convert_dtypes()- 将 DataFrame 列转换为支持的“最佳”数据类型pd.NA(pandas 对象用于指示缺失值)。

继续阅读以了解每种方法的更详细说明和用法。


1.to_numeric()

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

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

基本用法

输入to_numeric()是一个 Series 或 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

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

# convert Series
my_series = pd.to_numeric(my_series)

# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])

您还可以通过下列方法使用它来转换 DataFrame 的多个列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”被视为缺失/错误数值,而不是失败。我们可以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

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

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

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

向下转型

默认情况下,转换to_numeric()将为您提供int64float64dtype(或平台固有的任何整数宽度)。

这通常是您想要的,但是如果您想节省一些内存并使用更紧凑的 dtype(如)该怎么float32int8

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

2.astype()

astype()方法可让您明确说明 DataFrame 或 Series 所具有的数据类型。它非常灵活,您可以尝试从一种类型转换为任何其他类型。

基本用法

只需选择一种类型:您可以使用 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')

注意我说的是“尝试”——如果astype()不知道如何转换 Series 或 DataFrame 中的值,它将引发错误。例如,如果您有一个NaNinf值,则在尝试将其转换为整数时会出错。

从 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(即 2 8 - 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)


4.convert_dtypes()

1.0 及以上版本包含一种方法convert_dtypes(),将 Series 和 DataFrame 列转换为支持缺失值的最佳数据类型pd.NA

此处“最佳”是指最适合保存值的类型。例如,这是一个 pandas 整数类型,如果所有值都是整数(或缺失值):Python 整数对象的对象列转换为Int64NumPy 值的列int32,将成为 pandas dtype Int32

使用我们的objectDataFrame df,我们得到以下结果:

>>> df.convert_dtypes().dtypes                                             
a     Int64
b    string
dtype: object

由于列“a”保存的是整数值,因此它被转换为Int64类型(与不同,它能够保存缺失值int64)。

列“b”包含字符串对象,因此更改为 pandas 的stringdtype。

默认情况下,此方法将从每列中的对象值推断类型。我们可以通过传递以下内容来更改此设置infer_objects=False

>>> df.convert_dtypes(infer_objects=False).dtypes                          
a    object
b    string
dtype: object

现在,列“a”仍为对象列:pandas 知道它可以被描述为“整数”列(它在内部运行infer_dtype),但无法准确推断出它应该具有的整数数据类型,因此没有对其进行转换。列“b”再次转换为“字符串”数据类型,因为它被识别为保存“字符串”值。

解决方案 2:

使用这个:

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

解决方案 3:

下面的代码将改变列的数据类型。

df[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')

您可以指定您想要的数据类型,例如 str、float、int 等。

解决方案 4:

当我只需要指定特定的列并且想要明确时,我使用(每个pandas.DataFrame.astype):

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'})

解决方案 5:

pandas >= 1.0

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

更改熊猫中的列类型1.to_numeric()2.astype()3.infer_objects()4.convert_dtypes()pandas >= 1.0eg - 将列类型更改为字符串 #df 是你的数据框

转换为字符串很简单.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

解决方案 6:

df = df.astype({"columnname": str})

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

解决方案 7:

这是一个函数,它以 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'])

解决方案 8:

0.转换后保留整数类型

正如在 Alex Riley 的回答中所看到的,pd.to_numeric(..., errors='coerce')将整数转换为浮点数。

要保留整数,必须使用可空整数 Dtype,例如'Int64'。一种选择是调用.convert_dtypes()Alex Riley 的答案。或者直接使用.astype('Int64')

自 pandas 2.0 以来,另一个可用的选项是传递dtype_backend参数,这允许您在一次函数调用中转换 dtype。

df = pd.DataFrame({'A': ['#DIV/0!', 3, 5]})
df['A'] = pd.to_numeric(df['A'], errors='coerce').convert_dtypes()
df['A'] = pd.to_numeric(df['A'], errors='coerce').astype('Int64')

df['A'] = pd.to_numeric(df['A'], errors='coerce', dtype_backend='numpy_nullable')

以上所有内容都会产生以下转换:

更改熊猫中的列类型1.to_numeric()2.astype()3.infer_objects()4.convert_dtypes()pandas >= 1.0eg - 将列类型更改为字符串 #df 是你的数据框

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

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

from decimal import Decimal
df = pd.DataFrame({'long_float': ["0.1234567890123456789", "0.123456789012345678", "0.1234567890123456781"]})

df['w_float'] = df['long_float'].astype(float)       # imprecise
df['w_Decimal'] = df['long_float'].map(Decimal)      # precise

更改熊猫中的列类型1.to_numeric()2.astype()3.infer_objects()4.convert_dtypes()pandas >= 1.0eg - 将列类型更改为字符串 #df 是你的数据框

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

df['w_Decimal'] == Decimal(df.loc[1, 'long_float'])   # False, True, False
df['w_float'] == float(df.loc[1, 'long_float'])       # True, True, True

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

默认情况下,astype(int)转换为,如果数字特别长(例如电话号码),则int32它将不起作用( );请尝试(甚至):OverflowError`'int64'`float

df['long_num'] = df['long_num'].astype('int64')

附注:如果您得到SettingWithCopyWarning,则打开写时复制模式(有关详细信息,请参阅此答案)并再次执行您正在执行的操作。例如,如果您将col1和转换col2为浮点型,则执行以下操作:

pd.set_option('mode.copy_on_write', True)
df[['col1', 'col2']] = df[['col1', 'col2']].astype(float)

# or use assign to overwrite the old columns and make a new copy
df = df.assign(**df[['col1', 'col2']].astype(float))

3. 将整数转换为 timedelta

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

df = pd.DataFrame({'long_int': ['1018880886000000000', '1590305014000000000', '1101470895000000000', '1586646272000000000', '1460958607000000000']})
df['datetime'] = pd.to_datetime(df['long_int'].astype('int64'))
# or
df['datetime'] = pd.to_datetime(df['long_int'].astype(float))

df['timedelta'] = pd.to_timedelta(df['long_int'].astype('int64'))

更改熊猫中的列类型1.to_numeric()2.astype()3.infer_objects()4.convert_dtypes()pandas >= 1.0eg - 将列类型更改为字符串 #df 是你的数据框

4. 将 timedelta 转换为数字

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

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

更改熊猫中的列类型1.to_numeric()2.astype()3.infer_objects()4.convert_dtypes()pandas >= 1.0eg - 将列类型更改为字符串 #df 是你的数据框

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

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

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

更改熊猫中的列类型1.to_numeric()2.astype()3.infer_objects()4.convert_dtypes()pandas >= 1.0eg - 将列类型更改为字符串 #df 是你的数据框

6.astypeto_numeric

df = pd.DataFrame(np.random.default_rng().choice(1000, size=(10000, 50)).astype(str))
df = pd.concat([df, pd.DataFrame(np.random.rand(10000, 50).astype(str), columns=range(50, 100))], axis=1)

%timeit df.astype(dict.fromkeys(df.columns[:50], int) | dict.fromkeys(df.columns[50:], float))
# 488 ms ± 28 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df.apply(pd.to_numeric)
# 686 ms ± 45.8 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

解决方案 9:

创建两个数据框,每个数据框的列具有不同的数据类型,然后将它们附加在一起:

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

创建数据框后,您可以在第一列中使用浮点变量填充它,并在第二列中使用字符串(或您想要的任何数据类型)填充它。

解决方案 10:

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

 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   date    132 non-null    object 
 1   temp    132 non-null    float64

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

df['temp'] = df['temp'].astype('int64')

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

  #   Column  Non-Null Count  Dtype 
 ---  ------  --------------  ----- 
  0   date    132 non-null    object
  1   temp    132 non-null    int64 

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

解决方案 11:

从 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

解决方案 12:

假如您有各种对象列,例如此 Dataframe 包含 74 个对象列和 2 个整数列,其中每个值都有代表单位的字母:

import pandas as pd 
import numpy as np

dataurl = 'https://raw.githubusercontent.com/RubenGavidia/Pandas_Portfolio.py/main/Wes_Mckinney.py/nutrition.csv'
nutrition = pd.read_csv(dataurl,index_col=[0])
nutrition.head(3)

输出:

    name    serving_size    calories    total_fat    saturated_fat    cholesterol    sodium    choline    folate    folic_acid    ...    fat    saturated_fatty_acids    monounsaturated_fatty_acids    polyunsaturated_fatty_acids    fatty_acids_total_trans    alcohol    ash    caffeine    theobromine    water
0    Cornstarch    100 g    381    0.1g    NaN    0    9.00 mg    0.4 mg    0.00 mcg    0.00 mcg    ...    0.05 g    0.009 g    0.016 g    0.025 g    0.00 mg    0.0 g    0.09 g    0.00 mg    0.00 mg    8.32 g
1    Nuts, pecans    100 g    691    72g    6.2g    0    0.00 mg    40.5 mg    22.00 mcg    0.00 mcg    ...    71.97 g    6.180 g    40.801 g    21.614 g    0.00 mg    0.0 g    1.49 g    0.00 mg    0.00 mg    3.52 g
2    Eggplant, raw    100 g    25    0.2g    NaN    0    2.00 mg    6.9 mg    22.00 mcg    0.00 mcg    ...    0.18 g    0.034 g    0.016 g    0.076 g    0.00 mg    0.0 g    0.66 g    0.00 mg    0.00 mg    92.30 g
3 rows × 76 columns

nutrition.dtypes
name             object
serving_size     object
calories          int64
total_fat        object
saturated_fat    object
                  ...
alcohol          object
ash              object
caffeine         object
theobromine      object
water            object
Length: 76, dtype: object

nutrition.dtypes.value_counts()
object    74
int64      2
dtype: int64

将所有列转换为数字的一个好方法是使用正则表达式将单位替换为无,并使用 astype(float) 将列的数据类型更改为浮点数:

nutrition.index = pd.RangeIndex(start = 0, stop = 8789, step= 1)
nutrition.set_index('name',inplace = True)
nutrition.replace('[a-zA-Z]','', regex= True, inplace=True)
nutrition=nutrition.astype(float)
nutrition.head(3)

输出:

serving_size    calories    total_fat    saturated_fat    cholesterol    sodium    choline    folate    folic_acid    niacin    ...    fat    saturated_fatty_acids    monounsaturated_fatty_acids    polyunsaturated_fatty_acids    fatty_acids_total_trans    alcohol    ash    caffeine    theobromine    water
name
Cornstarch    100.0    381.0    0.1    NaN    0.0    9.0    0.4    0.0    0.0    0.000    ...    0.05    0.009    0.016    0.025    0.0    0.0    0.09    0.0    0.0    8.32
Nuts, pecans    100.0    691.0    72.0    6.2    0.0    0.0    40.5    22.0    0.0    1.167    ...    71.97    6.180    40.801    21.614    0.0    0.0    1.49    0.0    0.0    3.52
Eggplant, raw    100.0    25.0    0.2    NaN    0.0    2.0    6.9    22.0    0.0    0.649    ...    0.18    0.034    0.016    0.076    0.0    0.0    0.66    0.0    0.0    92.30
3 rows × 75 columns

nutrition.dtypes
serving_size     float64
calories         float64
total_fat        float64
saturated_fat    float64
cholesterol      float64
                  ...
alcohol          float64
ash              float64
caffeine         float64
theobromine      float64
water            float64
Length: 75, dtype: object

nutrition.dtypes.value_counts()
float64    75
dtype: int64

现在数据集很干净,您仅使用正则表达式和 astype() 即可对此 Dataframe 执行数字运算。

如果您想收集单位并粘贴在标题上,cholesterol_mg您可以使用以下代码:

nutrition.index = pd.RangeIndex(start = 0, stop = 8789, step= 1)
nutrition.set_index('name',inplace = True)
nutrition.astype(str).replace('[^a-zA-Z]','', regex= True)
units = nutrition.astype(str).replace('[^a-zA-Z]','', regex= True)
units = units.mode()
units = units.replace('', np.nan).dropna(axis=1)
mapper = { k: k + "_" + units[k].at[0] for k in units}
nutrition.rename(columns=mapper, inplace=True)
nutrition.replace('[a-zA-Z]','', regex= True, inplace=True)
nutrition=nutrition.astype(float)

解决方案 13:

我遇到了同样的问题。

我找不到任何令人满意的解决方案。我的解决方案就是将这些浮点数转换为 str,然后以这种方式删除“.0”。

就我而言,我只是将其应用于第一列:

firstCol = list(df.columns)[0]
df[firstCol] = df[firstCol].fillna('').astype(str).apply(lambda x: x.replace('.0', ''))

解决方案 14:

有没有办法在转换为 DataFrame 时指定类型?

是的。其他答案在创建 DataFrame 后转换 dtypes,但我们可以在创建时指定类型。根据输入格式使用DataFrame.from_records或。read_csv(dtype=...)

后者有时是必要的,以避免大数据的内存错误。


1.DataFrame.from_records

从所需列类型的结构化数组创建 DataFrame :

x = [['foo', '1.2', '70'], ['bar', '4.2', '5']]

df = pd.DataFrame.from_records(np.array(
    [tuple(row) for row in x], # pass a list-of-tuples (x can be a list-of-lists or 2D array)
    'object, float, int'       # define the column types
))

输出:

>>> df.dtypes
# f0     object
# f1    float64
# f2      int64
# dtype: object

2.read_csv(dtype=...)

如果您正在从文件读取数据,请使用dtype参数read_csv在加载时设置列类型。

例如,这里我们读取了 3000 万行,其中rating8 位整数genre为分类数据:

lines = '''
foo,biography,5
bar,crime,4
baz,fantasy,3
qux,history,2
quux,horror,1
'''
columns = ['name', 'genre', 'rating']
csv = io.StringIO(lines * 6_000_000) # 30M lines

df = pd.read_csv(csv, names=columns, dtype={'rating': 'int8', 'genre': 'category'})

在这种情况下,我们将加载时的内存使用量减半:

>>> df.info(memory_usage='deep')
# memory usage: 1.8 GB
>>> pd.read_csv(io.StringIO(lines * 6_000_000)).info(memory_usage='deep')
# memory usage: 3.7 GB

这是避免大数据内存错误的一种方法。加载并不总是能够更改数据类型,因为我们可能没有足够的内存来加载默认类型的数据。

解决方案 15:

我以为我遇到了同样的问题,但实际上我有一个小小的不同,这使得问题更容易解决。对于其他正在看这个问题的人来说,值得检查一下输入列表的格式。在我的例子中,数字最初是浮点数,而不是问题中的字符串:

a = [['a', 1.2, 4.2], ['b', 70, 0.03], ['x', 5, 0]]

但是,由于在创建数据框之前过多地处理列表,我丢失了类型并且所有内容都变成了字符串。

通过NumPy数组创建数据框:

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')

给出与问题中相同的数据框,其中第 1 列和第 2 列中的条目被视为字符串。但是

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')

确实给出了具有正确格式的列的数据框。

解决方案 16:

如果您想从字符串格式转换一列,我建议使用此代码“

import pandas as pd
#My Test Data
data = {'Product': ['A','B', 'C','D'],
          'Price': ['210','250', '320','280']}
data


#Create Data Frame from My data df = pd.DataFrame(data)

#Convert to number
df['Price'] = pd.to_numeric(df['Price'])
df

Total = sum(df['Price'])
Total

否则,如果您要将列值转换为数字,我建议您先过滤值并保存在空数组中,然后转换为数字。我希望此代码可以解决您的问题。

解决方案 17:

您可以在创建 DataFrame 后使用该pd.to_numeric函数来实现这一点。以下是如何将 DataFrame 中的第 2 列和第 3 列转换为浮点数:

import pandas as pd

table = [
    ['a', '1.2', '4.2'],
    ['b', '70', '0.03'],
    ['x', '5', '0'],
]

df = pd.DataFrame(table)

# Convert columns 2 and 3 to floats
df.iloc[:, 1:] = df.iloc[:, 1:].apply(pd.to_numeric, errors='coerce')

# Now, df contains the desired types for columns 2 and 3
print(df.dtypes)

运行代码片段Hide results展开片段

此方法在所需列上使用pd.to_numeric带有方法的函数。该参数可确保任何非数字值都转换为 NaN。apply`errors='coerce'`

这样,您不需要事先指定列类型,它会根据列的内容动态地将其转换为适当的类型。

相关推荐
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1265  
  IPD(Integrated Product Development)即集成产品开发,是一套先进的、成熟的产品开发管理理念、模式和方法。随着市场竞争的日益激烈,企业对于提升产品开发效率、降低成本、提高产品质量的需求愈发迫切,IPD 项目管理咨询市场也迎来了广阔的发展空间。深入探讨 IPD 项目管理咨询的市场需求与发展,...
IPD集成产品开发流程   17  
  IPD(Integrated Product Development)产品开发流程是一套先进的、被广泛应用的产品开发管理体系,它涵盖了从产品概念产生到产品推向市场并持续优化的全过程。通过将市场、研发、生产、销售等多个环节紧密整合,IPD旨在提高产品开发的效率、质量,降低成本,增强企业的市场竞争力。深入了解IPD产品开发...
IPD流程中TR   21  
  IPD(Integrated Product Development)测试流程是确保产品质量、提升研发效率的关键环节。它贯穿于产品从概念到上市的整个生命周期,对企业的成功至关重要。深入理解IPD测试流程的核心要点,有助于企业优化研发过程,打造更具竞争力的产品。以下将详细阐述IPD测试流程的三大核心要点。测试策略规划测试...
华为IPD   18  
  华为作为全球知名的科技企业,其成功背后的管理体系备受关注。IPD(集成产品开发)流程作为华为核心的产品开发管理模式,在创新管理与技术突破方面发挥了至关重要的作用。深入剖析华为 IPD 流程中的创新管理与技术突破,对于众多企业探索自身发展路径具有重要的借鉴意义。IPD 流程概述IPD 流程是一种先进的产品开发管理理念和方...
TR评审   16  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用