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
584 views
in Technique[技术] by (71.8m points)

python - Set maximum value (upper bound) in pandas DataFrame

I'm trying to set a maximum value of a pandas DataFrame column. For example:

my_dict = {'a':[10,12,15,17,19,20]}
df = pd.DataFrame(my_dict)

df['a'].set_max(15)

would yield:

    a
0   10
1   12
2   15
3   15
4   15
5   15

But it doesn't.

There are a million solutions to find the maximum value, but nothing to set the maximum value... at least that I can find.

I could iterate through the list, but I suspect there is a faster way to do it with pandas. My lists will be significantly longer and thus I would expect iteration to take relatively longer amount of time. Also, I'd like whatever solution to be able to handle NaN.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can use clip.

Apply to all columns of the data frame:

df.clip(upper=15)

Otherwise apply to selected columns as seen here:

df.clip(upper=pd.Series({'a': 15}), axis=1)

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

...