try 在单个df[_,_]表单中打印数据帧时,我看到数据帧错误.以下是代码行

#Data Frames code
import numpy as np
import pandas as pd

randArr = np.random.randint(0,100,20).reshape(5,4)
df =pd.DataFrame(randArr,np.arange(101,106,1),['PDS','算法','SE','INS'])
print(df['PDS','SE'])

错误:

Traceback (most recent call last): File "C:\Users\subro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\indexes\base.py", line 3621, in get_loc return self._engine.get_loc(casted_key) File "pandas\_libs\index.pyx", line 136, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\index.pyx", line 163, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas\_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: ('PDS', 'SE')

上述异常是以下异常的直接原因:

Traceback (most recent call last): File "D:\Education\4th year\1st sem\Machine Learning Lab\1st Lab\python\pandas\pdDataFrame.py", line 11, in <module> print(df['PDS','SE']) File "C:\Users\subro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\frame.py", line 3505, in __getitem__ indexer = self.columns.get_loc(key) File "C:\Users\subro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\indexes\base.py", line 3623, in get_loc raise KeyError(key) from err KeyError: ('PDS', 'SE')

推荐答案

你真的要这么做吗?在创建数据帧时需要指明列名,在提取数据帧切片时也需要使用双方括号df[[ ]]

import numpy as np
import pandas as pd

randArr = np.random.randint(0,100,20).reshape(5,4)
df = pd.DataFrame(randArr, columns=['PDS', 'SE', 'ABC', 'CDE'])
print(df)
print(df[['PDS','SE']])

输出:

   PDS  SE  ABC  CDE
0   56  77   82   42
1   17  12   84   46
2   34   9   19   12
3   19  88   34   19
4   51  54    9   94

   PDS  SE
0   56  77
1   17  12
2   34   9
3   19  88
4   51  54

Python相关问答推荐

如果值不存在,列表理解返回列表

为什么sys.exit()不能与subproccess.run()或subprocess.call()一起使用

Telethon加入私有频道

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

如何创建一个缓冲区周围的一行与manim?

与命令行相比,相同的Python代码在Companyter Notebook中运行速度慢20倍

下三角形掩码与seaborn clustermap bug

剪切间隔以添加特定日期

为什么调用函数的值和次数不同,递归在代码中是如何工作的?

从旋转的DF查询非NaN值

如何在Python Pandas中填充外部连接后的列中填充DDL值

Python:从目录内的文件导入目录

在round函数中使用列值

极点用特定值替换前n行

为什么这个正则表达式没有捕获最后一次输入?

如何将ManyToManyfield用于Self类

Parsel无法访问嵌套元素

为什么任何一个HTML页面在保存到文件后都会变大6个字节?

Networkx中K-Shell最核心的 node

对齐多个叠置多面Seborn CAT图