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

python - if statement plus concat results pandas

I have the following data frame.

df:

store_id items max percent store_name
1        4     15  26.6    blue
2        4     10  40.0    yellow
3        7     2   350.0   white
4        6     20  30.0    purple

I want to collect only the rows which are greater than or equal to 40%. The result should be a concatenation of the columns and rows that were greater than or equal to 40%. The net result is:

store_id items max percent store_name
2        4     10  40.0    yellow
3        7     2   350.0   white

and concatenation should be:

from store 2 - yellow, 4 items were selected out of 10 possible, with 40.0% achieved
from store 3 - white, 4 items were selected out of 2 possible, with 350.0% achieved

What I've attempted:

df = df[df.percent >= 40]

This returns the results I need but it is not part of an if statement as well as concatenate its results when true.

Any suggestions are greatly appreciated.

question from:https://stackoverflow.com/questions/65930915/if-statement-plus-concat-results-pandas

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

1 Answer

0 votes
by (71.8m points)
import pandas as pd
import numpy as np

df=pd.read_excel(r"D:Stack_overflowest9.xlsx")

df['concat']=np.where(df['percent'] >= 40, "From store "+df['store_id'].astype(str)+
                      " - "+df['store_name']+", "+df['items'].astype(str)+" items were selected out of "+
                      df['max'].astype(str)+" possible, with "+df['percent'].astype(str)+
                      "% achieved",'')

Try using Numpy. where conditions


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

...