简体   繁体   中英

Extracting the value from a Pandas Dataframe column that has only a unique value

Given a pandas DataFrame (df), where one column (unique_val_col) should have a unique value, what is the best the best way to extract this value (not as a list)?

So far I've used the following code:

output = list(set(df[unique_val_col)))

if len(output)==1:  output = output[0]

Or if there is a chance for nans then change the first line to be:

output = [val for val in list(set(df[unique_val_col))) if val == val]

The question is whether there is a more direct way, that would also reflect the fact that the column actually has only one value without needing the 'if' statement.

我认为您正在尝试查找仅出现一次的值,如果那样的话,您可以像这样实现它

df['unique_value_counts'].value_counts().sort_values(ascending=False).keys()[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM