Pythonize 函数应用于 pandas.Dataframe 对象中的列

标签 python pandas lambda dataframe list-comprehension

以下几行将 pandas.Dataframe 对象中的所有列转换为数字。

columns = ['a', 'b']
dft = pd.DataFrame(data=[['1','2'], ['3','4'],['5','6']], columns=columns)
for col in columns:
    dft[col] = pd.to_numeric(dft[col])

效果很好,但是 for ... in: 很难看。

我怎样才能说使用lambda函数和/或列表理解来让这个循环在一行中工作?

(我尝试了很多方法,但我不知道如何将 pd.to_numeric() 的结果分配给数据帧中每列的变量名称)

最佳答案

我在 github 中找到了解决方案.

print dft
print dft.dtypes
#   a  b  c
#0  1  2  5
#1  3  4  7
#2  5  6  9
#a    object
#b    object
#c    object
#dtype: object

dft1 = dft.apply(pd.to_numeric)

print dft1
print dft1.dtypes
#   a  b  c
#0  1  2  5
#1  3  4  7
#2  5  6  9
#a    int64
#b    int64
#c    int64
#dtype: object

dft[['a', 'b']] = dft[['a', 'b']].apply(pd.to_numeric)
print dft
print dft.dtypes
#   a  b  c
#0  1  2  5
#1  3  4  7
#2  5  6  9
#a     int64
#b     int64
#c    object
#dtype: object

下一个解决方案是使用convert_objects,但它会引发错误(v 0.17.0):

dft.convert_objects(convert_numeric=True)

FutureWarning: convert_objects is deprecated. Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

关于Pythonize 函数应用于 pandas.Dataframe 对象中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33947958/

相关文章:

python - 试图对投资金额求和,但一直说不可迭代

python - 如何将多个项目 append 到 pandas df?

python - 计算 Pandas 数据帧中的增长率

amazon-web-services - 使用 API 网关和无服务器框架在 AWS Lambda 上超过了速率

c# - 为什么不能在此lambda表达式中使用OrderBy()?

python - 对 Pandas 中 Python Lambda 函数的澄清/思考

python - 多次调用 pd.DataFrame.plot() 后颜色一致

python - ValueError : view limit minimum -5. 1000000000000005 小于 1 并且是无效的 Matplotlib 日期值

python - 转义字符串并立即将其分割

python - 从 df.columns 中删除不连续的重复项