我有一个列表hikari_col
它有两个值:column_name1
,column_name2
。 我还有一个数据帧df1
其中包含此值作为列名。 我正在尝试根据该hikari_col
列表检查数据帧df1
值。所以我在循环中将列表中的值作为数据帧中的列传递for
并检查它是否引发错误。
hikari_cols = ["column_name1", "column_name2"]
df1 = create_dfs("hikari", hikari_cols) # creating a df in another function
for hikari_col in hikari_cols: # looping over values in list (same as column names in df1)
try:
df1.hikari_col # Checking if column was created - It is, and its available as `df1.column_name1`
except: # But not as df1.hikari_col
return err_dict = {"error": "not found"}
但它每次都会例外。我做错了什么?
这是因为.
不适用于字符串,您必须将df.hikari_col
更改为df[hikari_col]
,但最有效的方法是:
hikari_cols = ["column_name1", "column_name2"]
df1 = create_dfs("hikari", hikari_cols) # creating a df in another function
if any(i not in df1.columns for i in hikari_cols):
err_dict = {"error": "not found"}