Pandas:使用callb转换为数字

2024-05-15 22:43:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下任一方法将数据帧的列和单元格值转换为float64:

df.infer_objects()

或者

df.apply(pd.to_numeric)

第一种方法将这些列保留为不可转换的对象类型,而第二种方法则在某些对象无法转换时引发异常。我的问题是,是否有可能提供我自己的错误/转换器回调函数?像这样:

def my_converter(value: object) -> float:
  # add all your "known" value conversions and fallbacks
  converted_value = float(value)
  return converted_value

df.apply(pd.to_numeric, converter=my_converted)

Tags: to数据对象方法dfvaluemyfloat
1条回答
网友
1楼 · 发布于 2024-05-15 22:43:04

我不知道有什么方法能简明扼要地按你的要求去做。不过,这将是对api的一个很好的补充。这是一个可行的方法,有点复杂。你知道吗

pd.to_numeric方法设置为不引发异常,而是使用errors参数返回NaN。使用您的NaNapply的位置可以创建特殊的转换器函数。现在使用add和参数fill_value=0添加使用pd.to_numeric和您的特殊转换器转换的数据帧。你知道吗

您可以在文档中找到^{}^{}的一些信息

它看起来像这样。你知道吗

import pandas as pd
import numpy as np


df = pd.DataFrame({ 'A': np.random.randn(5),
                    'B': np.random.randn(5)})

    A           B
0   -0.619165   1.310489
1   0.908564    1.017284
2   0.046072    -1.059349
3   1.123730    -2.229261
4   0.689580    -0.200981

df1 = df[df < 1] # This is your DataFrame from df.apply(pd.to_numeric, errors='coerce')
df1

    A           B
0   -0.619165   NaN
1   0.908564    NaN
2   0.046072    -1.059349
3   NaN         -2.229261
4   0.689580    -0.200981

df2 = df[df1.isnull()] 
df2 # This is the DataFrame you want to apply your converter df2.apply(my_converter)
df2 = df2.apply(lambda x: x*10) # This is my dummy special converter
df2

    A           B
0   NaN         13.104885
1   NaN         10.172835
2   NaN         NaN
3   11.237296   NaN
4   NaN         NaN

df1.add(df2, fill_value=0) # This is the final dataframe you're looking for

    A           B
0   -0.619165   13.104885
1   0.908564    10.172835
2   0.046072    -1.059349
3   11.237296   -2.229261
4   0.689580    -0.200981

相关问题 更多 >