如何在熊猫中将对象转换为 int 或 float

在加载的 excel 文件上使用 df.info 方法后,我得到以下数据


<class 'pandas.core.frame.DataFrame'>

RangeIndex: 30000 entries, 1 to 30000

Data columns (total 25 columns):

 #   Column      Non-Null Count  Dtype 

---  ------      --------------  ----- 

 0   Unnamed: 0  30000 non-null  object

 1   X1          30000 non-null  object

 2   X2          30000 non-null  object

 3   X3          29669 non-null  object

 4   X4          29677 non-null  object

 5   X5          30000 non-null  object

 6   X6          30000 non-null  object

 7   X7          30000 non-null  object

 8   X8          30000 non-null  object

 9   X9          30000 non-null  object

 10  X10         30000 non-null  object

 11  X11         30000 non-null  object

 12  X12         30000 non-null  object

 13  X13         30000 non-null  object

 14  X14         30000 non-null  object

 15  X15         30000 non-null  object

 16  X16         30000 non-null  object

 17  X17         30000 non-null  object

 18  X18         30000 non-null  object

 19  X19         30000 non-null  object

 20  X20         30000 non-null  object

 21  X21         30000 non-null  object

 22  X22         30000 non-null  object

 23  X23         30000 non-null  object

 24  Y           30000 non-null  object

dtypes: object(25)

memory usage: 2.9+ MB

我不知道为什么所有数据类型都是对象,尽管它们中的大多数都有数值 如何修复我的数据集的数据类型


慕的地8271018
浏览 136回答 2
2回答

慕姐8265434

让我们试试to_numericdf = pd.DataFrame({'1':['1','2'],'2':['a','b']})df = df.apply(pd.to_numeric,errors='ignore')查看df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 2 entries, 0 to 1Data columns (total 2 columns):&nbsp;#&nbsp; &nbsp;Column&nbsp; Non-Null Count&nbsp; Dtype&nbsp;---&nbsp; ------&nbsp; --------------&nbsp; -----&nbsp;&nbsp;0&nbsp; &nbsp;1&nbsp; &nbsp; &nbsp; &nbsp;2 non-null&nbsp; &nbsp; &nbsp; int64&nbsp;&nbsp;1&nbsp; &nbsp;2&nbsp; &nbsp; &nbsp; &nbsp;2 non-null&nbsp; &nbsp; &nbsp; objectdtypes: int64(1), object(1)memory usage: 88.0+ bytes

神不在的星期二

尝试例如:df['X1']&nbsp;=&nbsp;df['X1'].astype(str).astype(int)如果要格式化所有列,请尝试:df&nbsp;=&nbsp;df.astype(int)这是因为,当您导入.csv文件时,大部分列都被转换为对象。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python