首页 > 解决方案 > 读取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')

标签: pythonpandascsv

解决方案


同时指定标签和索引或列将引发 ValueError。因此,例如使用 "df.drop(['B', 'C'], axis=1)" 或 df.drop(columns=['B', 'C']) 。希望这会有所帮助


推荐阅读