【问题标题】:python pandas data frame error while trying to print it within single df[ _ , _ ] form尝试在单个 df[ _ , _ ] 表单中打印时出现 python pandas 数据框错误
【发布时间】:2022-08-06 22:22:11
【问题描述】:

尝试在单个 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\',\'Algo\',\'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\')

    标签: python pandas dataframe numpy random


    【解决方案1】:

    你的意思是这样做吗?创建数据框时需要注明列名,提取数据框切片时也需要双方括号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
    

    【讨论】:

      【解决方案2】:

      使用print(df[['PDS','SE']]) 格式而不是print(df['PDS','SE'])

      【讨论】:

      • 对,那是正确的! :-)
      猜你喜欢
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多