【问题标题】:Change data type of single or multiple columns of Dataframe in Python在 Python 中更改 Dataframe 的单列或多列的数据类型
【发布时间】:2020-12-02 02:28:42
【问题描述】:

我有一个数据框,我想更改不同列的数据类型。我已经制作了数据范围的架构,因为我在每一列中都有不同的数据类型。

import pandas as pd
import numpy as np
orders_schema = {
  '?dummy'              :np.int64,  
  '@timestamp'          :np.str,        
  '@version'            :np.int64,  
  'bytes'               :np.int64,  
  'c-geoip'             :np.str,    
  'c-isp'               :np.str,    
  'client'              :np.str,    
  'duration_usec'       :np.int64,  
  'forwarded_for'       :np.str,    
  'gtmcb'               :np.float64,
  'handling'            :np.str,    
  'hit_miss'            :np.str,  
  'host'                :np.str,  
  'method_urlv'         :np.str,    
  'ns__t'               :np.float64, 
  'ns_jspageurl'      :np.str,  
  'ns_referrer'         :np.str,    
  'parsed-useragent'    :np.str,    
  'port'                :np.int64,
  'referer'             :np.str,  
  'remote_user'         :np.str,  
  'request'             :np.str,  
  'nav'                 :np.str,  
  'pp'                  :np.str,  
  'profileid'           :np.float64,
  'source'              :np.str,    
  'titel'               :np.str,    
  'type'                :np.str,    
  'userid'              :np.str,    
  'uuid'                :np.str,    
  'status'              :np.int64,  
  'tags'                :np.str,    
  'time_first_byte'     :np.float64,    
  'topic'               :np.str,    
  'type'                :np.str,    
  'user-agent'          :np.str,  
  'version'             :np.str,    
  'lhost'               :np.str
}

但是,我不知道如何将此架构应用于现有数据框。我试过了

df_2.astype(orders_schema)
KeyError: 'Only a column name can be used for the key in a dtype mappings argument.'

您能否建议我如何更改列的数据类型?

提前致谢

【问题讨论】:

  • 请分享示例数据

标签: python pandas data-wrangling


【解决方案1】:

您只能在 order_schema 的键中提供列名。都是那些列名

【讨论】:

  • 确实它们都是列名,并且需要这些列的数据类型
  • 我认为任何一个列名都与您在字典中提供的内容不匹配,因为这就是错误的意思。能否请您提供 ss 或再次检查列名
  • 仔细检查列名没有问题
  • 如果可以的话可以分享一下ss吗
猜你喜欢
  • 2016-06-08
  • 2017-06-12
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多