我在Pandas中制作了一个DataFrame,并制作了如下的DataFrame。
if (a['conversion'] == line.strip().any()
or (a['x'] == line.strip().any()
or (a['y'] == line.strip().any()
or (a['z'] == line.strip().any():
generate(line)
所以基本上,我想检查x、y和z这两个键,但有些类型没有键"y"或"z"。因此引发了KeyError:"y"。
如何仅接近现有密钥?还是必须使用try/except?或者,如果我必须使用.get(['y](函数,我该如何实现它?(它并没有真正起作用(
您有两种方法:
-
检查列是否存在(跳跃前查看(:
if df['conversion'] == line.strip().any() or df['x'] == line.strip().any() # Checking if the columns are part of the dataframe or ('y' in df.columns and df['y'] == line.strip().any()) or ('z' in df.columns and df['z'] == line.strip().any()): generate(line)
或
columns = ('conversion', 'x', 'y', 'z') for column in columns: # If this column is not present, just keep looking if column not in df: continue if df[column] == line.strip().any(): generate(line) break
-
无论如何都要尝试访问该死的专栏(请求原谅比请求许可更容易(:
condition = False columns = ('conversion', 'x', 'y', 'z') for column in columns: try: # Update the condition using the or clause condition = df[column] == line.strip().any() except KeyError: # If the key is not present, just keep looking continue else: # Use short-circuiting if condition: generate(line) break