0

我有一个嵌套循环。在外循环中,我遍历比内循环中的数据帧[键]更多的键。这会导致 IndexError (key cannot be found in dataframe[key]。我需要一种方法来检查键是否匹配。

fe 只是关键列:

dfKeys                    dataframe
-------                   --------
 key                         key
  1                           1
  1                           3
  3                           5
  3                           9
  3
  4
  4
  5
  5
  5
  5
  8
  8
  9
  9
  9 

grouped=dfKeys.groupby('key')
for key, group in grouped:
    if ((group.someCol=='someVal').any() or ~(group.someCol.isin(someArray).any())):
        if(key in dataframe['key']): #######this did not solve it, always false (but there have to be some matches) 
            foundIndex=dataframe[dataframe['key']==key].index.values.astype(int)[0] #INDEXERROR after some loops if there is no 'if' above
            dataframe.loc[foundIndex,'myCol']='myVal'

类型dataframe['key']是熊猫系列。

4

2 回答 2

0

不优雅,但我可以使用 try-except

grouped=dfKeys.groupby('key')
for key, group in grouped:
    if ((group.someCol=='someVal').any() or ~(group.someCol.isin(someArray).any())):
        try: 
            foundIndex=dataframe[dataframe['key']==key].index.values.astype(int)[0] 
            dataframe.loc[foundIndex,'myCol']='myVal'
        except IndexError: print('key not found, continue')
于 2019-06-19T07:25:06.707 回答
0

If it's a list your looping through, then you can check if the index is within the length of the list:

if key < len(list):

If it's a dictionary you can check if the key exists:

if key in dict:

If you want to get a key from a dict if it exists, and return a default value if it doesn't, then you can use dict.get():

value = dict.get(key, default)

EDIT:

According to the documentation for pandas.Series, you can use the Series.get() method to get an item for a given key. Just as with dict.get() you can specify a default value to return if the key wasn't found:

if mySeries.get(myKey, 'default') != 'default':
    #This code will only run if it found `myKey` in `mySeries`

The pandas.Series documentation:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.html

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.get.html#pandas.Series.get

于 2019-06-18T00:46:00.873 回答