Select a pandas dataframe row where column has minimum value
A column name of df.S works but a column name of df.T doesn't work. df.T invokes the Transpose operation because it takes namespace precedence. Here's @ansev answer using literals instead.
df[df['S']==df['S'].min()]
row with minimum value of a column
Try this -
select top 1 * from table where N_UM = (select min(N_UM) from table);
Pandas GroupBy and select rows with the minimum value in a specific column
I feel like you're overthinking this. Just use groupby
and idxmin
:
df.loc[df.groupby('A').B.idxmin()]
A B C
2 1 2 10
4 2 4 4
df.loc[df.groupby('A').B.idxmin()].reset_index(drop=True)
A B C
0 1 2 10
1 2 4 4
Group Rows Based On Column Value And Keep Row With Minimum Value In R
You may check with order
and duplicated
all from base R
data = data[order(data$Mean),]
output = data[!duplicated(data[c("U","D")]),]
output
A B C U D E F G H I Mean Min Max
12 NA 2.00 Yes PQR-001 PQR B 11200077 -0.1 1.2 V 0.6914235 0.6907286 0.6919283
2 0.18 0.33 Yes ABC-001 ABC B 22000031 0.0 100.0 us 37.5211111 33.2500000 42.1200000
If you want dplyr
library(dplyr)
data %>% group_by(U, D) %>% slice(which.min(Mean))
how to subset rows in specific columns based on minimum values in individual columns in a dataframe using R
We can use map
to loop over the columns 'X0', 'V2', grouped by 'ID', slice the rows where the value is min
for that looped column, bind them together (_dfr
) and create the 'd' column with pmin
of those columns
library(dplyr)
library(purrr)
nm1 <- names(df1)[5:6]
map_dfr(nm1, ~ df1 %>%
group_by(ID) %>%
slice_min(!! rlang::sym(.x))) %>%
ungroup %>%
mutate(d = select(., all_of(nm1)) %>% reduce(pmin))
-output
# A tibble: 4 x 7
# X Y ID TI X0 V2 d
# <dbl> <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
#1 8.47 48.0 B_1 191. 0.134 0.348 0.134
#2 7.59 48.7 B_1_2 1350. 0.361 0.771 0.361
#3 8.15 48.4 B_1 191. 0.846 0.141 0.141
#4 8.06 48.2 B_1_2 1350. 0.983 0.224 0.224
Ignore NA values when using MIN function of apply
You can add na.rm=T
to your function and set to NA
when the entire vector of values is NA
(otherwise it returns it returns -Inf
).
my_min <- function(x) ifelse( !all(is.na(x)), min(x, na.rm=T), NA)
foo$MIN = apply(foo[c("A", "B")], 1, my_min)
output:
A B C MIN
1 1 3 NA 3
2 2 NA 1 2
3 3 2 2 3
4 NA NA 3 NA
Related Topics
How to Remove Elements of Array in Postgresql
Interesting Tree/Hierarchical Data Structure Problem
SQL Inner Join on Select Statements
Calculating Total Time Duration in MySQL
Using Reserved Word Field Name in Documentdb
What Does \ (Backslash) Mean in an SQL Query
Efficient Query to Split a Delimited Column into Separate Rows in Another Table
Preserve SQL Indexes While Altering Column Datatype
Group by Every N Records in T-Sql
Enable Full-Text Search on View with Inner Join
Retrieving a Row, with Data from Key-Value Pair Table in MySQL
Are There Downsides to Using Prepared Statements
What Is the Equivalent of Xml Path and Stuff in Linq Lambda Expression (Group_Concat/String_Agg)