我有一个 list hikari_col
它有两个值:column_name1
, column_name2
。
我还有一个数据框 df1
其中包含这些值作为列名称。
我正在尝试检查 df1
中的值基于此的数据框 hikari_col
列表。所以我从 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"}
关于python - Dataframe - 在循环中从变量列表中获取列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59817181/