准备

除了要安装pandas 还要安装openxl

建议数据的粮仓【创建文件】

导入
import pandas as pd

import pandas as pd

df= pd.DataFrame({
    "id":[1,2,3],
    "name":[1,2,3]
                  })


# 指定某个字段为索引 不然会默认多出一行作为索引
df.set_index("id")

# index=False 去除索引
df.to_excel("a.xlsx",index=False)

读取excel中的数据

import pandas as pd

# # header 可以指定column是第几行,也可以设置为None 那就是默认值了
people = pd.read_excel("ChinaNatureResource.xlsx",header=0)

# 多少行多少列
print(people.shape) # (2985, 12)

# 获得所有的列字段
print(people.columns)

# 也可以手动修改columns
print(people.columns['id',"......."])

"""
Index(['_id', '采矿权人', '发证机关)', '公告日期)', '开采方式', '开采主矿种', '矿山名称', '面积(km²)',
       '设计生产规模', '项目类型', '许可证号', '有效期)'],
      dtype='object')
"""

# 默认打印头信息 5 行 也可以指定3行
print(people.head(3))
"""
                        _id  ...                   有效期)
0  62217fd75f2cfe5458b98e89  ...  2022-01-09至2023-07-09
1  62217ff15f2cfe5458b98ea4  ...  2017-05-14至2020-12-21
2  62217ff15f2cfe5458b98ea6  ...  2022-02-17至2025-02-17
3  62217ff15f2cfe5458b98ea8  ...  2022-02-17至2025-02-17
4  62217ff15f2cfe5458b98eaa  ...  2022-02-17至2025-02-17
"""

print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@")

# 与上述相反 打印尾行,也可以自定义多少行
print(people.tail())

行列

import pandas as pd
# Series 和python中的字典很像
d={
    "x":100,
    "y":200,
    "z":300,
}

# 会把key转换为Index,value转换为data
# 生成序列
s1=pd.Series(d)

print(s1._data)# SingleBlockManager Items: Index(['x', 'y', 'z'], dtype='object') NumericBlock: 3 dtype: int64
print(s1.index) # Index(['x', 'y', 'z'], dtype='object')
print(s1.name) # None

也可以这么写

import pandas as pd


s1=[1,2,3]
l1=['x','y','z',]

ps=pd.Series(l1,s1) # Int64Index([1, 2, 3], dtype='int64')
ps=pd.Series(s1,l1) # Index(['x', 'y', 'z'], dtype='object')

将列放入 dataframe中

import pandas as pd

s1 = pd.Series([1, 2, 3], index=[1, 2, 3], name="A")
s2 = pd.Series([10, 20, 30], index=[1, 2, 3], name="B")
s3 = pd.Series([100, 200, 300], index=[1, 2, 3], name="C")

# 如何将上述 列 加到DataFrame

df = pd.DataFrame({s1.name: s1, s2.name: s2, s3.name: s3})
print(df)
"""
   A   B    C
1  1  10  100
2  2  20  200
3  3  30  300
"""

df1 = pd.DataFrame([s1,s2,s3])
print(df1)
"""
     1    2    3
A    1    2    3
B   10   20   30
C  100  200  300
"""

a1 = pd.Series([1, 2, 3], index=[1, 2, 3], name="A")
b2 = pd.Series([10, 20, 30], index=[1, 2, 3], name="B")
c3 = pd.Series([100, 200, 300], index=[2, 3, 4], name="C")
df2 = pd.DataFrame({a1.name: a1, b2.name: b2, c3.name: c3})
print(df2)
"""
     A     B      C
1  1.0  10.0    NaN
2  2.0  20.0  100.0
3  3.0  30.0  200.0
4  NaN   NaN  300.0
"""

数据填充  数据区域读取 填充数字

有一些数据 不会在第一行就出现,可能会跳过几行 那像这种 我们该如何处理这些数据呢?

import pandas as pd


books=pd.read_excel("a.xlsx",skiprows=6,usecols="C:F",index_col=None)
print(type(books["ID"])) # <class 'pandas.core.series.Series'>
  • skiprows 跳过六行,
  • usercols="C:F" 是只看 C到F这写列的数据
  • index_col 是指  把ID设置成前面的索引
  • dtype 设置 各个列的字段类型 但是系统不允许我们转换ID为int 所以我们需要转换为 字符串 str

调用 at函数  设置第1个 id为100

books["ID"].at[0]=100 # 设置第1个 id为100
# print(books)

源码

# 数据填充  数据区域读取 填充数字
"""
有一些数据 不会在第一行就出现,可能会跳过几行 那像这种 我们该如何处理这些数据呢?
"""
import pandas as pd
from datetime import date, timedelta

"""
# skiprows 跳过六行,
# usercols="C:F" 是只看 C到F这写列的数据
# index_col 是指  把ID设置成前面的索引
# dtype 设置 各个列的字段类型 但是系统不允许我们转换ID为int 所以我们需要转换为 字符串 str
# books=pd.read_excel("a.xlsx",skiprows=6,usecols="C:F",index_col=None,dtype={"ID":str,})
"""
books = pd.read_excel("a.xlsx", skiprows=6, usecols="C:F", index_col=None, dtype=str)
print(type(books["ID"]))  # <class 'pandas.core.series.Series'>

# 调用 at函数
# books["ID"].at[0]=100 # 设置第1个 id为100
# print(books)


# 设置时间
now_date = date(2022, 6, 3)

for i in books.index:  # books.index 就是 20 也就是这个数据一共的长度
    # 因为 i是从 0 开始的
    books["ID"].at[i] = i + 1
    # 如果i不被2整除就是No 否则就是yes
    books["Instore"].at[i] = "YES" if i % 2 == 0 else "NO"
    books['Date'].at[i] = now_date

print(books)

# 但是有一些小问题 这些id 都是浮点型的 float的

日期的处理

import pandas as pd
from datetime import date, timedelta

books = pd.read_excel("a.xlsx", skiprows=5, usecols="C:F", index_col=None, dtype=str)


# 调用 at函数
books["ID"].at[0]=100 # 设置第1个 id为100
# print(books)


# 设置时间
now_date = date(2022, 6, 3)

for i in books.index:
    books["ID"].at[i] = i + 1
    books["Instore"].at[i] = "YES" if i % 2 == 0 else "NO"
    books['Date'].at[i] = now_date+timedelta(days=i)
print(books)

# 但是有一些小问题 这些id 都是浮点型的 float的
# books.to_excel("b.xlsx",index=False)

如果day+1
日期+1

books['Date'].at[i] = now_date+timedelta(days=i)

如果年份+1

books['Date'].at[i] = date(now_date.year+i,now_date.month,now_date.day)

如果月份+1(需要逢12进1)

def add_mouth(d, md):
    """
    月份校验时间
    :param d: 当前年份
    :param md: 当前传入的月份
    :return:
    """
    # 传入的月份整除12 就是几年
    yd = md // 12
    # 取余
    m = d.month + md % 12

    if m != 12:
        yd += m // 12
        m = m % 12

    return date(d.year + yd, m, d.day)
books['Date'].at[i] = add_mouth(now_date, i)

还可以这么写

# books["ID"].at[i] = i + 1
books.at[i,'id'] = i+1

例子:

import os
# 这里我想指定某一路径,然后获取该路径下的文件
import re
import pandas as pd

def file_name(file_dir):
    """ root: 当前目录路径
        dirs: 当前路径下所有子目录
        files:当前路径下所有非目录子文件
    """
    for root, dirs, files in os.walk(file_dir):
        return files




file_name=file_name(r"C:\Users\zic\Desktop\Currency\Currency\spiders")

fp = open(r"C:\Users\zic\Desktop\Currency\Currency\pipelines.py", "r", encoding="utf-8").read()

spider_name = re.findall(r"spider\.name == \'(.*?)\'\:", fp)


file_name_list = []
for i in file_name:
    file_name_list.append(i[:-3])





now=[]
for spider in spider_name:
     for file in file_name_list:
          if file==spider:
               now.append(file)


df = pd.DataFrame.from_dict(
    {"能匹配上的": sorted(now),
     "文件列表": sorted(file_name_list),
     "管道里的": sorted(spider_name),

     },
     orient='index')

# df.set_index("a", inplace=True)

df.to_excel("B.xlsx")

函数填充和计算列

import pandas as pd


books=pd.read_excel("source/b.xlsx",index_col='ID')
# print(books)
books['Price'] = books['ListPrice']*books['Discount']
print(books)

第二种方式

import pandas as pd

books = pd.read_excel("source/b.xlsx", index_col='ID')

# for i in books.index:
#     books['Price'].at[i] = books['ListPrice'].at[i] * books['Discount'].at[i]
for i in range(5, 16):  # 仅仅计算5,16列的的
    books['Price'].at[i] = books['ListPrice'].at[i] * books['Discount'].at[i]

print(books)

每本书涨两块钱 如何计算

# 第一种方式
books['ListPrice'] += 2
print(books)


# 第二种方式 调用apply
def add_2(x):
    return x + 2


books['ListPrice'] = books['ListPrice'].apply(lambda x: x + 2)
print(books)

排序 多重排序

import pandas as pd


# index_col 指定那一列为索引
df = pd.read_excel("source/b.xlsx",index_col="ID")
# inplace 是在当前进行排序 而不会形成一个新的Dateframe
# ascending = True 是正向排序 false是反向排序
df.sort_values(by="ListPrice",inplace=True,ascending=False)
# 多重排序 后面是ascending 是列表是基于前面的by里面 进行倒还是正
df.sort_values(by=['Name',"Discount"],inplace=True,ascending=[True,False])

print(df)

数据过滤

要过滤18 到 30岁的数据

# _*_ coding: utf-8 _*_
# Time:     2022/7/3 22:33
# Author:   Chen ziChLiang
# Version:  V python3.9
# File:     08filter.py
import pandas as pd


def age_to_18_to_30(age):
    return 18 <= age <= 30


def level_filter(score):
    return 85 <= score <= 100


df = pd.read_excel("source/07filter.xlsx", index_col="ID")
student = df.loc[df['Age'].apply(age_to_18_to_30)]
print(student)

过滤18岁到30岁且分数 是85-100 分的

# _*_ coding: utf-8 _*_
# Time:     2022/7/3 22:33
# Author:   Chen ziChLiang
# Version:  V python3.9
# File:     08filter.py
import pandas as pd


def age_to_18_to_30(age):
    return 18 <= age <= 30


def level_filter(score):
    return 85 <= score <= 100


df = pd.read_excel("source/07filter.xlsx", index_col="ID")
student = df.loc[df['Age'].apply(age_to_18_to_30)].loc[df['Score'].apply(level_filter)]
print(student)

还可以这么写

student= df.loc[df.Age.apply(age_to_18_to_30)].loc[df.Score.apply(level_filter)]

用lambada 表达式

student = df.loc[df.Age.apply(lambda age: 18 <= age <= 30)].loc[df.Score.apply(lambda score: 85 <= score <= 100)]
print(student)

pandas 去重

下来介绍到就是用于数据去重的drop_duplicate方法
这个方法是对DataFrame格式的数据,去除特定列下面的重复行。返回DataFrame格式的数据。

这个方法里面有三个可填参数:
DataFrame.drop_duplicates(subset=None, keep=‘first’, inplace=False)

subset : column label or sequence of labels, optional 用来指定特定的列,默认所有列
keep : {‘first’, ‘last’, False}, default ‘first’ 删除重复项并保留第一次出现的项
inplace : boolean, default False 是直接在原来数据上修改还是保留一个副本

例如:
1、整行去重。
DataFrame.drop_duplicates()
2、按照其中某一列去重
DataFrame.drop_duplicates(subset=‘列名’)
3、只要是重复的数据,我都删除(例如有三个数字:1,2,1;执行之后变成:2;重复的都删除了)
DataFrame.drop_duplicates(keep=False)

下面给上第3中情况的代码

import pandas as pd
csv=pd.read_csv('E:/aaa/03.csv',low_memory=False,error_bad_lines=False)#读取csv中的数据
df = pd.DataFrame(csv)
print(df.shape)#打印行数
f=df.drop_duplicates(keep=False)#去重
print(f.shape)#打印去重后的行数
f.to_csv('E:/aaa/distionct_03.csv',index=None)#写到一个新的文件

合并并且去重 且 保留第一次出现的值

import pandas as pd


df1 = pd.read_excel("总表.xlsx", sheet_name="Sheet1")
df2 = pd.read_excel("总表.xlsx", sheet_name="Sheet2")

result = pd.concat([df1,df2])
print(result)
result.drop_duplicates(keep="first")
result.to_excel("last_replite.xlsx",index=None)