过滤数据
import pandas as pd
# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40]}
df = pd.DataFrame(data)
# Filter rows where Age is greater than 30
filtered_df = df[df['Age'] > 30]
print(filtered_df)
分组和聚合数据
# Grouping by a column and calculating the mean
grouped = df.groupby('Age').mean()
print(grouped)
处理缺失数据
# Check for missing values
missing_values = df.isnull().sum()
# Fill missing values with a specific value
df['Age'].fillna(0, inplace=True)
将函数应用于列
# Applying a custom function to a column
df['Age'] = df['Age'].apply(lambda x: x * 2)
连接DataFrames
# Concatenate two DataFrames
df1 = pd.DataFrame({'A': ['A0', 'A1'], 'B': ['B0', 'B1']})
df2 = pd.DataFrame({'A': ['A2', 'A3'], 'B': ['B2', 'B3']})
result = pd.concat([df1, df2], ignore_index=True)
print(result)
合并DataFrames
# Merge two DataFrames
left = pd.DataFrame({'key': ['A', 'B', 'C'], 'value': [1, 2, 3]})
right = pd.DataFrame({'key': ['B', 'C', 'D'], 'value': [4, 5, 6]})
merged = pd.merge(left, right, notallow='key', how='inner')
print(merged)
数据透视表
# Creating a pivot table
pivot_table = df.pivot_table(index='Name', columns='Age', values='Value')
print(pivot_table)
处理日期时间数据
# Converting a column to DateTime
df['Date'] = pd.to_datetime(df['Date'])
数据重塑
# Melting a DataFrame
melted_df = pd.melt(df, id_vars=['Name'], value_vars=['A', 'B'])
print(melted_df)
使用分类数据类型
# Encoding categorical variables
df['Category'] = df['Category'].astype('category')
df['Category'] = df['Category'].cat.codes
数据采样
# Randomly sample rows from a DataFrame
sampled_df = df.sample(n=2)
计算累计和
# Calculating cumulative sum
df['Cumulative_Sum'] = df['Values'].cumsum()
删除重复项
# Removing duplicate rows
df.drop_duplicates(subset=['Column1', 'Column2'], keep='first', inplace=True)
快捷进行onehot编码
dummy_df = pd.get_dummies(df, columns=['Category'])
导出数据
df.to_csv('output.csv', index=False)
为什么要加上导出数据呢?,因为在导出数据时一定要加上index=False参数,这样才不会将pandas的索引导出到csv中。
总结
这15个Pandas代码片段将大大增强您作为数据科学家的数据操作和分析能力。将它们整合到的工作流程中,可以提高处理和探索数据集的效率和效率。