python - 读取csv文件中索引列的问题
问题描述
我正在读取熊猫中的 csv 文件。当我打印 df.shape 时,它显示正确的行数和列数,但是当我尝试删除某些列时,由于未定义列名,它显示错误。这是我的代码:
df = pd.read_csv('Weather_data.csv',sep=',',header=0,parse_dates=["datetime_utc"])
print(df.columns)
print(df.head())
print(df.shape)
它打印为 (98913, 20),当我尝试删除列时,它显示错误
df.drop(columns=['_fog','_hail','_rain','_snow','_thunder','_tornado','_wdire','_windchillm','_wgustm'],axis=1,inplace=True])
这是引发的关键错误:
KeyError: "['_fog' '_hail' '_rain' '_snow' '_thunder' '_tornado' '_wdire'\n '_windchillm' '_wgustm'] not found in axis"
请告诉为什么会发生这种情况 df.columns 的结果:
Index(['datetime_utc', ' _conds', ' _dewptm', ' _fog', ' _hail',
' _heatindexm', ' _hum', ' _precipm', ' _pressurem', ' _rain', '_snow',
' _tempm', ' _thunder', ' _tornado', ' _vism', ' _wdird', ' _wdire',
' _wgustm', ' _windchillm', ' _wspdm'],
dtype='object')
解决方案
同时指定标签和索引或列将引发 ValueError。因此,例如使用 "df.drop(['B', 'C'], axis=1)" 或 df.drop(columns=['B', 'C']) 。希望这会有所帮助
推荐阅读
- c# - 如何实例化泛型类
- xml - Powershell 中的 XML 解析
- azure - 在虚拟机上运行命令失败并阻止其他“Invoke-AzureRmVMRunCommand”
- python - 在 Pandas 中,在 grouby 和 pd.cut 之后,如何重新排列数据框以随时间按每个 bin 绘制?
- maven - Maven,替换文件中的令牌以进行调试和编译
- javascript - 如何访问 JS 函数
- kubernetes - Openshift 4.2 OLM - 操作员依赖
- javascript - MDC - 无法初始化文本输入
- oracle-apex - 在交互式报告中使用页面项目的动态 where 子句不起作用
- gradle - 如何使用 Gradle 为包文档配置 Dokka?