已解决(pandas读取DataFrame列报错)raise KeyError(key) from err KeyError: (‘name‘, ‘age‘)

已解决(pandas读取DataFrame列报错)raise KeyError(key) from err KeyError: (‘name‘, ‘age‘)







报错代码


粉丝群里的一个小伙伴想输出name和age两列的数据;

import pandas as pd
import numpy as np

df = pd.DataFrame(data={
    
    
    "name": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
    "age": [23, 26, 37, 46, 85, 12, 53, 80, 66, 32],
    "score": [13, 23, 22, 76, 56, 89, 99, 100, 10, 54],
})

print(df['name', 'age'])

报错截图


在这里插入图片描述

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "E:/Python/test3.py", line 10, in <module>
    print(df['name','age'])
  File "D:\Python3.8\lib\site-packages\pandas\core\frame.py", line 3505, in __getitem__
    indexer = self.columns.get_loc(key)
  File "D:\Python3.8\lib\site-packages\pandas\core\indexes\base.py", line 3623, in get_loc
    raise KeyError(key) from err
KeyError: ('name', 'age')


报错翻译


报错信息翻译

将KeyError(键)从err中提升
值错误:(‘name‘, ‘age‘)



报错原因


报错原因:pandas读取多列是需要两个中括号包着



解决方法


修改代码为:

import pandas as pd
import numpy as np

df = pd.DataFrame(data={
    
    
    "name": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
    "age": [23, 26, 37, 46, 85, 12, 53, 80, 66, 32],
    "score": [13, 23, 22, 76, 56, 89, 99, 100, 10, 54],
})

print(df[['name', 'age']])

再次运行成功:


在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yuan2019035055/article/details/126163742