python显示所选列中具有NULL值的行中的第一个单元格



假设我有这个csv数据:

id_column   col_name2   col_name3   
id1         value1      value1      
id2         value2                  
id3                     value2      
id4         value3                         
#User selects number 3 (related to col_name3), I do
df = pandas.read_csv("file.csv")
col=df.columns[3]
df_col = pandas.read_csv("file.csv", usecols=[col])
#print(df_col.isnull())
#maybe iterate through df_col values to catch NULL values 
#print only id2 and id4

如何只显示与col_name3上的NULL单元格相关的id2和id4?

我让用户选择列,例如,如果用户像上面一样选择了col_name3,我想自动显示id_column中的id,其中所选col_name3中存在NULL值。

因此,如果用户选择col_name3,则只应显示id2和id4。如果用户选择了col_name2,则应仅显示id3。

如果我正确理解你,你想做的应该是这样的:

df = pd.DataFrame({'name': ['id1', 'id2', 'id3'], 'a': [20, None, 30], 'b': [10, 40, None]})
df[df.isna().any(axis=1)].iloc[:, 0]

将导致:df2, df3

解释:

df.isna()将为我们带来所有的null。.any(axis=1)将使列轴上至少有1个空值(与.all()相反(。

最后,.iloc[:, 0]会给我们第一列,这不是必须的,只有当你想要第一列时(如果你想要所有至少有一个null的列,请删除(。

编辑以回答您的编辑:

为了由用户选择列,我们将添加input:

chosen_column = input(f"Please choose one of the following columns: {list(df.columns)}")
# Filter by na and display only the chosen column
df[df.isna().any(axis=1)][chosen_column]

我希望我能正确理解你,这就是你的目标。

您可以为此目的创建一个自定义函数:

def print_id(col,df=df):
df=df.copy()
if isinstance(col,list):
return df.loc[df[col].isna().any(1),'id_column'].reset_index(drop=True)
else:
return df.loc[df[col].isna(),'id_column'].reset_index(drop=True)

最后调用该函数(用户输入(:

print_id('col_name3')
#OR
print_id('col_name3',df)
#OR
print_id(['col_name3','col_name2'])
#OR
print_id(['col_name3','col_name2'],df)

如果您想输入2并选择col_name2,则使用:

def print_id(like,df=df):
if isinstance(like,list):
print('like parameter doesn't support multiple values')
return None
else:
df=df.copy()
return df.loc[df.filter(like=str(like)).isna().any(1),'id_column'].reset_index(drop=True)

最后调用该函数(用户输入(:

print_id(2)
#OR
print_id(3,df)

相关内容

最新更新