pandas数据处理

113 阅读2分钟

pandas

  1. 性能很高

  2. 有容易使用的数据结构

  3. 更容易使用的数据分析工具

Pandas数据读取

image.png 在这里,数据库可以直接使用pd.read_sql来读取

读取CSV

数据结构

image.png

series

一种类似于一维数组的对象,由一组数据和一组与之相关的数据标签(索引)组成

实例程序

import pandas as pd
import pymysql

# conn = pymysql.connect(
#     host = '127.0.0.1',
#     user='root',
#     password="Wys231471.com",
#     database='md600'
# )

# mysql_page = pd.read_sql("select * from support",con=conn)

# print(mysql_page.head(3))

#使用默认索引
s1 = pd.Series([1,2,3,'4dde',5])
print(s1)
print(s1.index)
print(s1.values)

# 使用具有标签索引的series
s1 = pd.Series([1,2,3,'4dde',5],index=['no.1','no.2','no.3','no.4','no.5'])
print(s1)
print(s1.index)
print(s1.values)

# 使用python字典创建series
d={
    "a":"this is a",
    'b':'this is b'
}

s3=pd.Series(d)
print(s3)
print(s3['a'])
print(s3[['a','b']])


# DataFrame

data ={
    'name':['rraion','kafen'],
    'age':[19,22]
}

df = pd.DataFrame(data)
print(df)
print(df.dtypes)
print(df.columns)
print(df.index)

# 从dataframe里面抽取数据,抽取一列就是series,抽取多列就是dataframe
print(df['name']) #查询一列
print(df[['name','age']]) #查询多列

# 查询行
print(df.loc[1])# 查询1行
print(df.loc[1:2])# 查询多行


查询方式


import pandas as pd

df =pd.read_csv("./md600.csv")

print(df.head)

df.set_index('cmd',inplace=True)
print(df.index)
print("-------------------------")

# 替换数据,略

# 使用单个label值查询数据
print(df.loc['A12','sms_receive'])
print("-------------------------")
print(df.loc['A12',['sms_receive','sms_transfer']])
print("-------------------------")

# 使用值列表批量进行查询
print(df.loc[['A12','A13'],'sms_receive'])
print("-------------------------")
print(df.loc[['A12','A13'],['sms_receive','sms_transfer']])

#使用数值区间进行查询
print(df.loc['A12':'A72',['sms_receive','sms_transfer']])
print(df.loc['A12':'A72','sms_transfer':'gprs_receive'])## 多行多列

# 使用条件进行查询
print(df.loc[df['sms_receive']>'',:])# 相当于是布尔查询
print("-------------------------")

# 调用函数查询
def query_data(df):
    return df.index.str.startswith("A")&(df['gprs_receive']>'')

print(df.loc[query_data,:])# 相当于是布尔查询

# pandas 新增和修改数据列
df.loc[:,'sms_receive']=df['sms_receive'].str.replace('xxx','new').astype('int32') #清除单位,变成数字类型
# 计算温差

# df.apply 方法,可以使用一个函数

# https://www.bilibili.com/video/BV1UJ411A7Fs?p=5&vd_source=67def8b47cf8e23054144d1dcc4412c8