pandas Python Dataframe检查变量列中是否存在名称

bkhjykvo  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(133)

我希望我的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
eufgjt7s

eufgjt7s1#

我想这个能满足你的要求

if cols_df['main_col'] in df.columns and '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
print('','df =',df,sep='\n')
print('','cols_df =',cols_df,sep='\n')

输出:

Aux col not in df

df =
    A   B
0  10   0
1  20  10
2  30  20

cols_df =
main_col    A
aux_col     B
dtype: object

相关问题