📅  最后修改于: 2023-12-03 15:18:13.920000             🧑  作者: Mango
Pandas is a powerful library in Python used for data manipulation and analysis. It provides various functionalities to manipulate data frames and perform operations on them. In this article, we will discuss if-else statements in pandas and how they can be used to manipulate data frames.
The syntax for if-else statements in pandas is as follows:
df.loc[df['column_name'] condition, 'new_column_name'] = 'value_if_true' if df['column_name'] condition else 'value_if_false'
where,
df
is the name of the dataframecolumn_name
is the name of the column on which the condition is to be appliedcondition
is the conditional statement to be checkednew_column_name
is the name of the new column to be createdvalue_if_true
is the value to be assigned if the condition is truevalue_if_false
is the value to be assigned if the condition is falseLet's consider the following data frame:
import pandas as pd
data = {'Name': ['John', 'Emma', 'Mark', 'Jessica', 'Sam'],
'Age': [22, 24, 21, 19, 23],
'Gender': ['Male', 'Female', 'Male', 'Female', 'Male'],
'Marks': [75, 80, 64, 78, 82]}
df = pd.DataFrame(data)
print(df)
Output:
Name Age Gender Marks
0 John 22 Male 75
1 Emma 24 Female 80
2 Mark 21 Male 64
3 Jessica 19 Female 78
4 Sam 23 Male 82
Let's say we want to add a column named Pass/Fail
based on the marks obtained. If marks are greater than or equal to 70, the value assigned should be Pass
, otherwise Fail
. We can achieve this using if-else statements in pandas.
df.loc[df['Marks'] >= 70, 'Pass/Fail'] = 'Pass'
df.loc[df['Marks'] < 70, 'Pass/Fail'] = 'Fail'
print(df)
Output:
Name Age Gender Marks Pass/Fail
0 John 22 Male 75 Pass
1 Emma 24 Female 80 Pass
2 Mark 21 Male 64 Fail
3 Jessica 19 Female 78 Pass
4 Sam 23 Male 82 Pass
In the above example, we have used if-else statements in pandas to create a new column named Pass/Fail
based on the marks obtained by the students. If the marks are greater than or equal to 70, the value assigned is Pass
, otherwise Fail
.
Pandas if-else statements are a useful tool for manipulating data frames in Python. They can be used to create new columns based on conditional statements, which can help in data analysis and visualization.