pandas高级操作

pandas高级操作

1.替换操作

  • 替换操作可以同步作用于Series和DataFrame中
  • 单值替换
  • 普通替换;替换所有符合要求的元素
  • 按照指定单值替换: to_replace={列标签:替换值} value='新值'
  • 多值替换
  • 列表替换: to_replace=[],value=[]
  • 字典替换:(推荐) to_replace={ro_replace:value,to_replace:value}
df=DataFrame(data=np.random.randint(0,100,size=(5,6)))

df.replace(to_replace=2,value='Two')

df.replace(to_replace={3:'three'})

df.replace(to_replace={4:62},value='five')

2.映射操作

2.1 map

  • 注意:map是Series的方法,只能被Series调用
  • 概念:创建一个映射关系列表,把values元素和一个特定的标签或者字符串绑定(给一个元素值提供不同的表达方式)

dic={
    'name':['张三','李四','张三'],
    'salary':[15000,20000,15000]
}
df=DataFrame(data=dic)
df

dic1={
    '张三':'tom',
    '李四':'jack'
}
df['e_name']=df['name'].map(dic)
  • 当运算工具

dic={
    'name':['张三','李四','张三'],
    'salary':[15000,20000,15000]
}
def after_sal(s):
    if s>3000:
        s=s-(s-3000)*0.5
    return s

df['after_sal']=df['salary'].map(after_sal)
  • lambda表达式操作
data['href'].map(lambda x:True if x in [1,2,3] else False)

2.2.apply 和 applymap

  • apply:
  • 参数是一列 (axis=0)或一行 (axis=1)的数据
  • 作用行或列的元素是 DataFrame的运算工具
def get_field(a):
  index,content_list=a
data.loc[:,['index','novel_content_list']].apply(get_field,axis=1)
  • applymap,作用到每个元素 【每个元素都会执行get_field函数】
def get_field(a):
    print(a)
data.loc[:2,['index','novel_content']].applymap(get_field)

3.排序实现的随机抽样

  • take()
  • np.random.permutation()
df=DataFrame(data=np.random.randint(0,100,size=(100,3)),columns=['A','B','C'])

np.random.permutation(10)

df.take(np.random.permutation(3),axis=1).take(np.random.permutation(100),axis=0)

4.数据的分类处理

  • groupby()函数
  • groups属性查看分组情况
df = DataFrame({
    'item':['Apple','Banana','Orange','Banana','Orange','Apple'],
    'price':[4,3,3,2.5,4,2],
    'color':['red','yellow','yellow','green','green','green'],
    'weight':[12,20,50,30,20,44]
})

df.groupby(by='item')

df.groupby(by='item') .get_group(("price",30000))

df.groupby(by='item').groups
  • 分组聚合

df.groupby(by='item',as_index=False)['price'].mean()

dic=df.groupby(by='color')['weight'].mean().to_dict()

df['mean_w']=df['color'].map(dic)

5.高级数据聚合

  • 使用 groupby分组后,也可以使用 transformapply提供自定义函数实现更多的运算
  • df.groupby('item')['price'].sum()<==>df.groupby('item')['price'].apply(sum)<!--==-->
  • transformapply都会进行运算,在 transform或者 apply中传入函数即可
  • transformapply也可以传入一个 lambda表达式
  • agg(),分组后进行多种不同的聚合操作
df = DataFrame({
    'item':['Apple','Banana','Orange','Banana','Orange','Apple'],
    'price':[4,3,3,2.5,4,2],
    'color':['red','yellow','yellow','green','green','green'],
    'weight':[12,20,50,30,20,44]
})

def my_mean(s):
    m_sum=0
    for i in s:
        m_sum+=i
    return m_sum/len(s)

df.groupby(by='item')['price'].transform(my_mean)

df.groupby(by='item')['price'].transform(my_mean)

df.groupby(by='item')['price'].apply(my_mean)
df.groupby('district')['salary'].agg(['min','max','mean'])

6.透视表

  • 概念
  • 透视表是一种可以对数据动态排布并且分类汇总的表格格式,pivot_table
  • 优点
  • 灵活性高,可以随意定制分析计算要求
  • 脉络清晰易于理解数据
  • 操作性强,报表神器
  • 重要参数
  • index:分类汇总的条件
    • 每一个pivot_table必须拥有一个index
  • values:需要对计算的数据进行筛选
  • columns:设置列层次字段
    • 对values字段再进行分类
  • aggfunc:设置对数据聚合时进行的函数操作
    • 当我们未设置aggfunc时,他默认aggfunc=’mean’计算均值
df=pd.read_csv('./data/透视表-篮球赛.csv',encoding='utf8')

df.pivot_table(index=['主客场','胜负'],values=['得分','篮板','助攻'],aggfunc='sum')

df.pivot_table(index='主客场',values='得分',columns='对手',aggfunc='sum',fill_value=0)

7.交叉表

  • 是一种用于计算分组的特殊透视图,对数据进行汇总
  • pd.crosstab(index,columns)
  • index:分组数据,交叉表的行索引
  • columns:交叉表的列索引
df = DataFrame({
    'sex':['man','man','women','women','man','women','man','women','women'],
    'age':[15,23,25,17,35,57,24,31,22],
    'smoke':[True,False,False,True,True,False,False,True,False],
     'height':[168,179,181,166,173,178,188,190,160]
})

pd.crosstab(df.smoke,df.sex)

Original: https://blog.csdn.net/m0_46926492/article/details/124316199
Author: 荼靡,
Title: pandas高级操作

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/751855/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球