更改Pandas中列的数据类型 - Change data type of columns in Pandas

问题:

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

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. 我能够保证的是,每一列都包含相同类型的值。 oop


解决方案:

参考一: https://stackoom.com/question/14fz4/更改Pandas中列的数据类型
参考二: https://oldbug.net/q/14fz4/Change-data-type-of-columns-in-Pandas
相关文章
相关标签/搜索