python模块pandas库常用操作小结

记录一些个人在python的pandas库常用的操作的小结,方便后续开发记录,同时助人助己。

持续更新中

按数据格式,读取excel、csv等,输出列名、获取总量。

import os
import pandas as pd
import numpy as np
from progressbar import ProgressBar

if __name__ == "__main__":
    folderpath = os.getcwd()  # 获取当前工作目录路径
    pathfile = folderpath + '\\' + '文件.xlsx'
    types_path = {'源端':str, '宿端':str}
    pathlist = pd.read_excel(pathfile,sheet_name=0,usecols=[1,6,8],dtype=types_path)
    #其中sheet_name=0表示第一张sheet表,usecols=[1,6,8]表示只读取其中第2,7,9列,dtype表示按照某指定格式读入
    tilte = pathlist.columns #获取列名
    count = len(pathlist) #获取总量

获得某一行某一列的元素

print(df.at[a,'B']) #获取第a行,列名为B的元素

2.1 删除

删除某一行(注:删除后index不会自动变化)

df= df.drop(a) #删除index=a的一行

按某几列为关键词,删除重复项

df.drop_duplicates(subset=['AA','BB','CC'],keep='first',inplace=True)
#删除AA,BB,CC列都一样的重复项,keep=first保留第一条,inplace=True更改原有df

删除空白行,并订正index索引

df=df.dropna().reset_index(drop=True)

删除符合特定条件的行

resultlist = resultlist.drop(resultlist[resultlist['A'].str.contains('A列中需要删除')].index)
resultlist = resultlist.drop(resultlist[].index)

2.2 字典

生成字典,并对应字典查找

'''
字典形如:
celname celid
谢晋  1042500
崔嵬  1031007
祝希娟 1305487
陈强  1043190
王苹  1322505
张良  1316341

需要生成:
{'谢晋':'1042500','崔嵬':'1031007'}

'''
if __name__ == "__main__":
    folderpath = os.getcwd()  # 获取当前工作目录路径
    prizelistfile = folderpath + '\\' + 'pri.xlsx'
    mapfile = folderpath + '\\' + 'celurl.xlsx'
    targetpath = folderpath + '\\' + 'year.xlsx'
    types = {'celname':str, 'celid':int}
    prilist = pd.read_excel(prizelistfile)
    maplist = pd.read_excel(mapfile, dtype=types)
    maplist.set_index('celname',drop=True, append=False, inplace=True)
    count = prilist.shape[1]
    celmap=maplist.to_dict('dict')['celid']
    celmap = dict(celmap) #生成字典
    for i in range(0,count) :
        prilist.iloc[:, i] = prilist.iloc[:, i].map(celmap) #在字典中查找对应
    print("**************")
    print(prilist)
    prilist.to_excel(targetpath,index=False)

使用字典替换代换内容

vc = {'VC1': 1, 'VC2':2, 'VC3':3}
pathlist['list'] = pathlist['list'].map(vc)

2.3 生成新dataframe并导出

arr = []
for i in range(0,len(pf_source)):
        source = str(pf_source['源'][i])
        des = str(pf_source['宿'][i])
        path = get_path(source,des)
        arr.append([source, path])
pf_target = pd.DataFrame(arr,columns = ['源','路径'])

2.4 合并

pf3= pd.concat([pf1,pf2],ignore_index=True)
#将pf1与pf2联合,重新生成index

2.5 修改

按照某一列数值生成内容

#方法1: np.where
apl['涨跌'] = np.where(apl[3]>0,'涨',np.where(apl[3]==0,'平','跌'))

#方法2: np.select
conditions = [apl[3]>0,apl[3]==0,apl[3] 0:
        return '涨'
    elif number == 0:
        return '平'
    else:
        return '跌'

 df['涨跌'] = df['p_change'].map(number_to_flag)

#方法4: lambda
def do_merchant(x,y):
    return y/x
A_2Vehicle_count['vehicle_count']=map(lambda x,y:do_merchant(x,y),A_2Vehicle_count['ave_time'],A_2Vehicle_count['sum_time'])

2.6 分类汇总

分类汇总

total = df.groupby(by=['a'])['b'].sum()
意思是对字段a进行分组然后通过字段B进行求和汇总
返回Series类型对象。 a会变成index b则成为值
total=total.to_frame().reset_index()
#转换为dataframe

3.1 Series转换为dataFrame并修改索引

total=total.to_frame().reset_index()

Original: https://blog.csdn.net/weixin_40173467/article/details/123367853
Author: SilverSofa
Title: python模块pandas库常用操作小结

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

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

(0)

大家都在看

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