pandas常用函数

# -*- coding: utf-8 -*-
# @Time    : 2023/4/19 1:59 下午
# @Author  : dubaichuan
# @File    :pandas常用函数.py
# @Software: PyCharm

import pandas as pd

# 构建数据
df1 =pd.DataFrame({'X1':[1,2,3,4,5,5],'X2':[2,3,4,5,6,4]})
print(df1)

df  = pd.DataFrame([
    ['green','A'],
    ['red','B'],
    ['blue','C']
])
print(df)

print(df.shape) # 查看行列 (3, 2)
df.info() # 查看数据基本信息 object ---> str
print(df.describe()) # 查看数据描述信息
print(df1.columns) # 获取列名 RangeIndex(start=0, stop=2, step=1)
print(df.head()) # 获取前几行数据,默认获取前5行
print(df.tail()) # 获取后几行数据,默认获取后5行

# 获取字段'1' 中为A的数据
'''
       0  1
0  green  A
1    red  B
2   blue  C
'''
print(df[df[1]=='A'])

# 修改字段名
df.columns = ['color','class']
print(df)
'''
    color class
0  green     A
1    red     B
2   blue     C
'''
# 独热处理  obj ----> uint8 离散型数据
df = pd.get_dummies(df)
print(df)
'''
   color_blue  color_green  color_red  class_A  class_B  class_C
0           0            1          0        1        0        0
1           0            0          1        0        1        0
2           1            0          0        0        0        1
'''

# 交叉表
df1 = pd.DataFrame({'类别': ['水果', '水果', '水果', '蔬菜', '蔬菜', '肉类', '肉类'],
                    '产地': ['美国', '中国', '中国', '中国', '新西兰', '新西兰', '美国'],
                    '水果': ['苹果', '梨', '草莓', '番茄', '黄瓜', '羊肉', '牛肉'],
                    '数量': [5, 5, 9, 3, 2, 10, 8],
                    '价格': [5, 5, 10, 3, 3, 13, 20]
                    })

print(df1)
'''
   类别   产地  水果  数量  价格
0  水果   美国  苹果   5   5
1  水果   中国   梨   5   5
2  水果   中国  草莓   9  10
3  蔬菜   中国  番茄   3   3
4  蔬菜  新西兰  黄瓜   2   3
5  肉类  新西兰  羊肉  10  13
6  肉类   美国  牛肉   8  20
'''
# 按照类别和产地,进行频数统计,统计各特征之间的频数
print(pd.crosstab(df1['类别'],df1['产地']))
'''
产地  中国  新西兰  美国
类别             
水果   2    0   1
肉类   0    1   1
蔬菜   1    1   0
'''
print(pd.crosstab(df1['类别'],df1['产地'],margins=True))
'''
产地   中国  新西兰  美国  All
类别                   
水果    2    0   1    3
肉类    0    1   1    2
蔬菜    1    1   0    2
All   3    2   2    7
'''


# 皮尔逊系数 ----> 相关系数
# 【-1,1】  -----> 相关性越接近1 表示正相关越强 相关性越接近-1 表示负相关越强
alldf = pd.DataFrame({
    'x': [0, 1, 2, 4, 7, 10],
    'y': [0, 3, 2, 4, 5, 7],
    's': [0, 1, 2, 3, 4, 5],
    'c': [5, 4, 3, 2, 1, 0]
})
print(alldf)
'''
    x  y  s  c
0   0  0  0  5
1   1  3  1  4
2   2  2  2  3
3   4  4  3  2
4   7  5  4  1
5  10  7  5  0
'''

print(alldf.corr())
'''
          x         y         s         c
x  1.000000  0.941729  0.972598 -0.972598
y  0.941729  1.000000  0.946256 -0.946256
s  0.972598  0.946256  1.000000 -1.000000
c -0.972598 -0.946256 -1.000000  1.000000
'''

alldf.to_csv('1.csv')
alldf.to_json('1.json')
alldf.to_excel('1.xlsx')

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值