python可以一次性将一组列转换为数字

python可以一次性将一组列转换为数字,python,pandas,Python,Pandas,我将.csv加载到数据帧(df)中,并将一列一列转换为数字: df = pd.read_csv(fullPath, converters={'Total requests received': lambda x: pd.to_numeric(x, errors='coerce'), 'Requests Processed': lambda x: pd.to_numeric(x, errors='coerce'

我将.csv加载到数据帧(df)中,并将一列一列转换为数字:

 df = pd.read_csv(fullPath, converters={'Total requests received': lambda x: pd.to_numeric(x, errors='coerce'),
                                           'Requests Processed': lambda x: pd.to_numeric(x, errors='coerce'),
                                           'Requests still being processed': lambda x: pd.to_numeric(x, errors='coerce')})

有没有一种方法可以将所有列一次性转换为数字,而不必逐个命名?

最近也有同样的问题。您应该能够使用dtype指定何时读取csv。查看此问题和下面的代码:

需要注意的是,此解决方案将尝试将每一列读取为int或float(尽管您可以将dtype指定为dict{col:dtype},但这不是您的问题)。

如果您想要numpy类型,请查看以下内容:

或者,@Harv Ipan的回答也很好,并且将实现同样的目标。尽管有额外的迭代


最后,考虑一下你是否真的需要这个。Pandas通常在解释类型方面做得很好,但我假设您有一些特定的用例

最近也有同样的问题。您应该能够使用dtype指定何时读取csv。查看此问题和下面的代码:

需要注意的是,此解决方案将尝试将每一列读取为int或float(尽管您可以将dtype指定为dict{col:dtype},但这不是您的问题)。

如果您想要numpy类型,请查看以下内容:

或者,@Harv Ipan的回答也很好,并且将实现同样的目标。尽管有额外的迭代

最后,考虑一下你是否真的需要这个。Pandas通常在解释类型方面做得很好,但我假设您有一些特定的用例

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

# this will make everything a float, so no truncation occurs
df = pd.read_csv(file_path, dtype=float)

# or if you aren't afraid of truncation
df = pd.read_csv(file_path, dtype=int)