Home >Backend Development >Python Tutorial >Tutorial on deleting row data using pandas
pandas tutorial: How to use pandas to delete row data, specific code examples are required
Introduction:
In data analysis and processing, data often needs to be cleaned And processing, deleting unnecessary or invalid rows of data in a data set is a common operation. In Python, the pandas library provides powerful data manipulation tools. This article will introduce how to use pandas to delete row data and give specific code examples.
import pandas as pd
data = {'Name': ['Zhang San', 'Li Si', 'Wang Wu', 'Zhao Liu', 'Liu Qi'],
'年龄': [20, 25, 30, 35, 40], '性别': ['男', '男', '女', '男', '女']}
df = pd.DataFrame(data)
print("Original data:")
print(df)
Output result:
Original data:
Name Age Gender
0 Zhang San 20 Male
1 Li Si 25 Male
2 Wang Wu 30 Female
3 Zhao Liu 35 Male
4 Liu Qi 40 Female
df = df[df['age']
print("Delete data with age greater than or equal to 30:")
print(df)
Output result:
Delete data whose age is greater than or equal to 30:
Name Age Gender
0 Zhang San 20 Male
1 Li Si 25 Male
df = df.drop([0, 4])
print("Delete the first and last rows of data:")
print(df)
Output results:
Delete the first and last rows of data:
Name, Age, Gender
1 Li Si 25 Male
2 Wang Wu 30 Female
3 Zhao Liu 35 Male
df = df.drop(df.index[[1, 2]])
print("Delete the data in the second and third rows:")
print(df)
Output result:
Delete the second and third rows of data:
Name Age Gender
0 Zhang San 20 Male
3 Zhao Liu 35 Male
df.drop(df[df['age'] >= 30].index, inplace=True)
print("Directly delete the age greater than Data equal to 30: ")
print(df)
Output result:
Delete data whose age is greater than or equal to 30 directly on the original data:
Name Age Gender
0 pieces Three 20 Male
1 Li Si 25 Male
Conclusion:
By using the pandas library and the above code example, we can easily delete row data in the DataFrame object. Through conditions, index labels or row numbers, we can selectively delete rows of data that meet specific conditions. This provides us with very convenient tools and methods for data cleaning and processing.
The above is the detailed content of Tutorial on deleting row data using pandas. For more information, please follow other related articles on the PHP Chinese website!