如何在Pandas中访问数据框架的特定元素.给错误



我有一个数据框df_params。它包含存储过程的参数。

PurchaseOrderID   OrderDate SupplierReference     DF_Name
0                1  2013-01-01          B2084020  dataframe1
1                2  2013-01-01            293092  dataframe2
2                3  2013-01-01          08803922  dataframe3
3                4  2013-01-01         BC0280982  dataframe4
4                5  2013-01-01         ML0300202  dataframe5

我只是想在循环中访问数据框架的元素:

for i in range(len(df_params)):
print(df_params[i][0])

但是它给了我一个错误,没有真正的解释:

Traceback (most recent call last):
File "C:mypathsite-packagespandascoreindexesbase.py", line 2897, in get_loc
return self._engine.get_loc(key)
File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 0
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Test3.py", line 35, in <module>
print(df_params[i][0])
File "C:UsersmypathPython37libsite-packagespandascoreframe.py", line 2995, in __getitem__
indexer = self.columns.get_loc(key)
File "C:UsersmypathPython37libsite-packagespandascoreindexesbase.py", line 2899, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 0
PS Microsoft.PowerShell.CoreFileSystem::\mypath>
目标是为存储过程提供值:
for i in range(len(df_params)):
query = "EXEC Purchasing.GetPurchaseOrder " + df_params[i][0] + "," + str(df_params[i][1]) + "," + df_params[i][2])
df = pd.read_sql(query, conn)

期望的输出结果:

EXEC Purchasing.GetPurchaseOrder 1, '2013-01-01', 'B2084020'
EXEC Purchasing.GetPurchaseOrder 2, '2013-01-01', '293092'
EXEC Purchasing.GetPurchaseOrder 3, '2013-01-01', '08803922'
EXEC Purchasing.GetPurchaseOrder 4, '2013-01-01', 'BC0280982'
EXEC Purchasing.GetPurchaseOrder 5, '2013-01-01', 'ML0300202'

pandas.DataFrames的行为不完全像numpy.ndarrays。基本上有三个选项:

选项1:iterrows-method:您可以遍历pandas的行。dataframe

for idx, row in df_params.iterrows():
print(row['PurchaseOrderID'])

这是一个特别可读的方式,所以我个人更喜欢这个

选项2:索引:如果你想索引熊猫。数据框架就像numpy一样。narray对象,使用方法.iat[]

for i in range(len(df_params)):
print(df_params.iat[i, 0])

这实际上索引了所有元素,而忽略了数据框架的索引!所以假设你有一个不同的索引(在极端的一些字符串或表与pandas.DataTimeIndex)这仍然是有效的…就像你会做一个df_params.to_numpy()[i, 0]注意:存在一个使用列名的类似函数:.at[]

还有第二种方法来索引pandas.DataFrame对象,它对于列来说更安全:.loc[]。它接受索引和列名 。
for idx in df_params.index:
print(df_params.iloc[idx, 'PurchaseOrderID'])

选项3:切片熊猫。系列对象:pandas.DataFrame中的每一列都是一个pandas.Series对象,您可以对其进行类似于numpy.ndarray的索引(实际上您按照上面描述的方法索引系列):

col = df_params['PurchaseOrderID']
for idx in col.index:
print(col[idx])

那么在你的情况下出了什么问题?双索引几乎与上一个示例相同,但是它在底层调用.loc[],因此需要一个列名,而不是一个数字(这可能是.iloc[]方法)。它期望首先看到列,然后是行。如果你想的话,你可以这样写:

for i in range(len(df_params)):
print(df_params.iloc[0][i])

这只适用于您的pandas.DataFrame具有从0开始的连续数字索引!所以请不要这样做,并使用您的表的实际索引(实际上使用上面的一个选项,而不是最后一个;))

在数据帧上有更好的访问值的方法,您可以使用lambda。使用lambda可以访问任意行。

df.apply(lambda row : print(row['DF_Name']))

现在变量'row'是数据框上的每一行,您可以访问该行上的每个属性。

最新更新