熊猫数据框列的 KeyError 异常

时间:2021-01-05 14:11:36

标签: python pandas dataframe error-handling

想象一个人想要制作一个接受两种数据帧的函数 - 有列“值”和没有。 (比如说,这是来自不同来源的资产数据,有些来源没有提供有关价值的信息。)

函数 foo 应该根据数据框运行不同的过程,例如,将 "Value" 复制到新列“B”或使用 1 添加新列“B”。一个玩具示例如下。

import pandas as pd

df1 = pd.DataFrame({"A":["one", "two", "three"]})
df2 = pd.DataFrame({"A":["one", "two", "three"], "Value":[1, 2, 3]})

KeyError: 'Value' 的情况下处理 df1 的最佳方法是什么。

def foo(df, col_name="Value"):

    <if col_name exists>
        df["B"] = df[col_name] 
    <else>
        df["B"] = 1
    return df

1 个答案:

答案 0 :(得分:2)

试试:

df['B'] = df.get('Value', 1)

或等效

df['B'] = df['Value'] if 'Value' in df else 1