更改Pandas中列的数据类型

£可爱£侵袭症+ 提交于 2020-08-16 12:08:58

问题:

I want to convert a table, represented as a list of lists, into a Pandas DataFrame. 我想将表示为列表列表的表转换为Pandas DataFrame。 As an extremely simplified example: 作为一个极其简化的示例:

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

What is the best way to convert the columns to the appropriate types, in this case columns 2 and 3 into floats? 将列转换为适当类型的最佳方法是什么,在这种情况下,将列2和3转换为浮点数? Is there a way to specify the types while converting to DataFrame? 有没有一种方法可以在转换为DataFrame时指定类型? Or is it better to create the DataFrame first and then loop through the columns to change the type for each column? 还是先创建DataFrame然后遍历各列以更改各列的类型更好? Ideally I would like to do this in a dynamic way because there can be hundreds of columns and I don't want to specify exactly which columns are of which type. 理想情况下,我想以动态方式执行此操作,因为可以有数百个列,并且我不想确切指定哪些列属于哪种类型。 All I can guarantee is that each columns contains values of the same type. 我可以保证的是,每一列都包含相同类型的值。


解决方案:

参考一: https://stackoom.com/question/14fz4/更改Pandas中列的数据类型
参考二: https://oldbug.net/q/14fz4/Change-data-type-of-columns-in-Pandas
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!