pandas 常用技巧记录

一、设置展示

import pandas 
# 设置最大显示行数为50
pd.set_option('display.max_rows', 50)
# 设置最大显示列数为10
pd.set_option('display.max_columns', 10)
# 设置每列的最大宽度为50个字符
pd.set_option('display.max_colwidth', 50)
# 显示所有行
pd.set_option('display.max_rows', None)
# 显示所有列
pd.set_option('display.max_columns', None)
# 重置所有选项到默认值
pd.reset_option('all')
二、apply、map添加进度条
import pandas as pd
from tqdm import tqdm
tqdm.pandas(desc='正在处理数据记录') 
# 创建一个DataFrame
data = {'col1': [1, 2, 3, 4, 5], 'col2': [6, 7, 8, 9, 10],'col3': ["苹果","橘子","香蕉","香蕉","香蕉"]}
df = pd.DataFrame(data)

# 定义一个处理函数
def process_row(x):
    # 这里可以添加你的处理逻辑,这里只是一个示例
    return x * 2

df['col4'] = df.progress_apply(lambda x:process_row(x['col1']),axis=1)
df['col5'] = df['col1'].progress_map(process_row)

三、多列赋值

def generate_multi(x):
    x1=x*2
    x2=x**2
    x3=x*3
    return [x1,x2,x3]


#赋值多列,方法一
df['res'] = df['col1'].map(generate_multi)
df['res1'] = df['res'].map(lambda x:x[0])
df['res2'] = df['res'].map(lambda x:x[1])
df['res3'] = df['res'].map(lambda x:x[2])

#赋值多列,方法二
df[['res4','res5','res6']]=df.apply(lambda x: generate_multi(x['col1']),axis=1,result_type='expand')

四、多指标聚合函数

df.groupby("col3").agg(["mean", "sum"])
df.groupby("col3").agg( avg_a=("col1", "mean"),sum_a=("col2", "sum"),min_c=("col1","min"),)

五、其他小技巧

#正则替换
df['col6'] = df['col3'].str.replace("","",regex=True)
dt['col7'] = dt['col3'].str.replace("[^\w\u4e00-\u9fa5]","",regex=True)
print (df[['col3','col6']]) #逻辑取反 df[~df['col3'].isin(['香蕉','苹果'])] #按值计数与比列 print (df['col6'].value_counts(normalize=False)) print (df['col6'].value_counts(normalize=True))

#根据类型选择列
df.select_dtypes(include=["int64", "float64"])

 

 

 

posted @ 2024-06-25 16:23  glowwormss  阅读(6)  评论(0编辑  收藏  举报