Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

python - Minimum value for each row in pandas dataframe

im trying to compute the minimum for each row in a pandas dataframe.

I would like to add a column that calculates the minimum values and ignores "NaN" and "WD"

For example

A   B   C   D
1   3   2   WD
3   WD  NaN 2

should give me a new column like

Min
1
2

I tried df.where(df > 0).min(axis=1) and df.where(df != "NaN").min(axis=1) without success

question from:https://stackoverflow.com/questions/65682198/minimum-value-for-each-row-in-pandas-dataframe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Convert values to numeric with non numeric to NaNs by errors='coerce' in to_numeric and DataFrame.apply so is possible use min:

df['Min'] = df.apply(pd.to_numeric, errors='coerce').min(axis=1)
print (df)
   A   B    C   D  Min
0  1   3  2.0  WD  1.0
1  3  WD  NaN   2  2.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...