我希望我的dataframe有两列。我不知道它们的名字是什么。我想通过一个变量来分配它们。我想检查其中一列是否不可用,然后创建这个新列Code:
# Columns dataframe or series. It contains names of the actual columns
# I get below information from another source
cols_df = pd.Series(index=['main_col'],data=['A'])
# This also the dataframe I get from another source
df = pd.DataFrame(data={'A':[10,20,30]})
# My job is see if the given dataframe has two columns
if (cols_df['main_col'] in df.columns) and (cols_df['aux_col'] not in df.columns):
print("Aux col not in df")
cols_df['aux_col'] = 'B'
df[cols_df['aux_col']] = df[cols_df['main_col']]-10
当前输出:
_check_indexing_error will raise
KeyError: 'aux_col'
预期输出:
df =
A B
0 10 0
1 20 10
2 30 20
cols_df =
main_col A
aux_col B
1条答案
按热度按时间eufgjt7s1#
我想这个能满足你的要求
输出: