I see dataframe error while trying to print it within single df[ _ , _ ] form. Below are the code lines

#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'])

errors:

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')

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

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')

推荐答案

Do you mean to do this? Need to indicate the column names when creating the dataframe, and also need double square brackets df[[ ]] when extracting a slice of the dataframe

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']])

Output:

   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相关问答推荐

如何在 django 的 django-ckeditor 中添加自定义模板

如何在 Python 中加载 Bloomberg Live 曲线

python 全局运算符仿真

不附加可迭代对象时可以使用列表理解吗

按质心、剪辑或其他方式过滤形状多边形?

使用 QPainter.drawLine() 时 PySide6 应用程序崩溃

如何将“user_id”传递给 CustomerSerializer?

失败的线程进程是否存在适当的 PEP 错误?

不能从另一个目录执行 Python 导入

如何在 pandas 中使用 count、groupby 和 max?

OpenCV 中的裁剪返回旋转 90 度的图像

即使在使用 Explicit 后也无法在元素中获取全文 - Selenium Python 中的 WebDriverWait

如何使用包含连字符的键定义 TypedDict 类

将批处理图像文件从子文件夹复制到父文件夹

Pandas 数组过滤 NaN 并保留组中的第一个值

为列值的唯一组合创建 ID 号

一次替换多个字符

如果 altair 中有多个 y 轴,如何增加标签间距和刻度间距?

满足以下约束的纸浆程序 min(a,b) > min(x,y)

复制 X 次特定行的 pandas 数据帧