[英]How let second condition be evaluated only when first one is met?
I made a DataFrame in Pandas and made a DataFrame like below.我在 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)
so basically, I would like to check both keys x, y and z but some types does not have key 'y' or 'z'.所以基本上,我想检查两个键 x、y 和 z,但有些类型没有键 'y' 或 'z'。 So KeyError: 'y' was raised.所以 KeyError: 'y' 被提出。
How can I only approach existing keys?我怎样才能只接近现有的钥匙? or do I have to use try/except?还是我必须使用try/except? or if I have to use.get(['y]) function, how can I implement it?或者如果我必须使用.get(['y]) function,我该如何实现它? (it did not really work) (它并没有真正起作用)
You have two approaches:你有两种方法:
Check if a column exists (Look Before You Leap):检查列是否存在(在您跳跃之前查看):
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)
or或者
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
Try to access the damn column anyway (Easier to Ask for Forgiveness than Permission):无论如何都要尝试访问该死的列(请求宽恕比许可更容易):
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.