add column and put desired value depending on the condition [duplicate] - python

This question already has answers here:
Pandas conditional creation of a series/dataframe column
(13 answers)
Closed 8 months ago.
screenshot of the dataframe table
I want to have another column name final grade that will get the average grade and checks if the average grade is greater than > or equal = to 75. And if so put 'Passed' and if not put 'FAILED'
df_exams['Final Grade'] = 'PASSED' if df_exams.loc[(df_exams['Average Grade'] >= 75)] else 'FAIL'
Can someone help me I am a newbie and want to be a Data Analyst. Thanks in advance

You need to use apply with a lambda function. The example below is from geeksforgeeks. Hope it helps!
df['Result'] = df['Maths'].apply(lambda x: 'Pass' if x>=5 else 'Fail')

Related

set a column based on other columns in pandas [duplicate]

This question already has answers here:
Pandas conditional creation of a series/dataframe column
(13 answers)
Closed 10 months ago.
I'm trying to set a column based on the value of other columns in my dataframe, but i'm having a hard time with the syntax of this. I can best describe this with an example:
Say you have a dataframe: the columns "Computer", "IP", "IP2" "Signal", "Connected"
data = {'Computer':['cp1', 'cp2'], 'IP1':[51.20, 51.21], IP2:[52.20, 52.21], 'Signal':[IN, OUT]}
df = pd.DataFrame(data)
df[Connected]=np.nan
Here's what I've tried:
for i in df['Signal']:
if i =='IN':
df['Connected']= df['IP2']
else: df['Connected'] =df[IP1]
But this doesn't give me the correct output.
What I would like as an output is for every instance of 'IN' Connected takes the value of IP2
And for every instance of 'OUT' it takes the value of IP1
I hope this makes sense. Thank you
Use mask with the right condition
df['Connected'] = df['IP1'].mask(df['Signal'] == 'IN', df['IP2'])
df
Out[20]:
Computer IP1 IP2 Signal Connected
0 cp1 51.20 52.20 IN 52.20
1 cp2 51.21 52.21 OUT 51.21

Delete multiple rows by multiple conditions in python [duplicate]

This question already has answers here:
delete rows based on a condition in pandas
(2 answers)
Closed 1 year ago.
I have a simple dataset:
I want to delete the rows where count>1 when animal is cat or dog. So the output should look like:
Can I get the result in an efficient way? Thank you
count_mask = dataset['count'] > 1
animal_mask = dataset['animal'].isin(['cat', 'dog'])
dataset = dataset[~(count_mask & animal_mask)]

How to put a condition while using a GroupBy in Pandas? [duplicate]

This question already has answers here:
How do I select rows from a DataFrame based on column values?
(16 answers)
Closed 2 years ago.
I have used the following code to make a distplot.
data_agg = data.groupby('HourOfDay')['travel_time'].aggregate(np.median).reset_index()
plt.figure(figsize=(12,3))
sns.pointplot(data.HourOfDay.values, data.travel_time.values)
plt.show()
However I want to choose hours above 8 only and not 0-7. How do I proceed with that?
What about filtering first?
data_filtered = data[data['HourOfDay'] > 7]
# depending of the type of the column of date
data_agg = data_filtered.groupby('HourOfDay')['travel_time'].aggregate(np.median).reset_index()
plt.figure(figsize=(12,3))
Sns.pointplot(data_filtered.HourOfDay.values, data_filtered.travel_time.values)
plt.show()

Value is being returned as None [duplicate]

This question already has answers here:
How do I select rows from a DataFrame based on column values?
(16 answers)
Closed 3 years ago.
I am trying to return all correct data when a condition is met. I would like to return all the relevant records when there has been X amount of goals scored by the home team.
data = pd.read_csv("epl_data_v2.csv")
def highest_home_score():
data.loc[data['HG']==1]
The console is returning the value None. I'm not sure why this happens. I know the column name 'HG' is correct.
def highest_home_score():
print(data.loc[data['HG']==1])
highest_home_score()
The code above produces what I was expecting - a small set of results that feature 1 as the HG value.

Columns in Pandas Dataframe [duplicate]

This question already has answers here:
Binning a column with pandas
(4 answers)
Closed 3 years ago.
I have a dataframe of cars. I have its car price column and I want to create a new column carsrange that would have values like 'high','low' etc according to car price. Like for example :
if price is between 0 and 9000 then cars range should have 'low' for those cars. similarly, if price is between 9000 and 30,000 carsrange should have 'medium' for those cars etc. I tried doing it, but my code is replacing one value to the other. Any help please?
I ran a for loop in the price column, and use the if-else iterations to define my column values.
for i in cars_data['price']:
if (i>0 and i<9000): cars_data['carsrange']='Low'
elif (i<9000 and i<18000): cars_data['carsrange']='Medium-Low'
elif (i<18000 and i>27000): cars_data['carsrange']='Medium'
elif(i>27000 and i<36000): cars_data['carsrange']='High-Medium'
else : cars_data['carsrange']='High'
Now, When I run the unique function for carsrange, it shows only 'High'.
cars_data['carsrange'].unique()
This is the Output:
In[74]:cars_data['carsrange'].unique()
Out[74]: array(['High'], dtype=object)
I believe I have applied the wrong concept here. Any ideas as to what I should do now?
you can use list:
resultList = []
for i in cars_data['price']:
if (i>0 and i<9000):
resultList.append("Low")
else:
resultList.append("HIGH")
# write other conditions here
cars_data["carsrange"] = resultList
then find uinque values from cars_data["carsrange"]

Categories