python-Excel vlookup功能学习

声明:优化的项目越来越难做,使用python工具助理于优化项目,减少重复工作。减少加班啊!希望通信相关的同学们一起交流学习!本人刚开始学习,不知地方请大家指出谢谢。

今日学习python 对于excel中的Vlookup功能。
1.使用的包是import pandas as pd;
2.函数使用的是merge();
3.直接用pandas的merge方法会形成笛卡尔积,原因是子表表中有重复的(子表是指excel中公式运行的表)。要先对子表进行去重。

import pandas as pd
#用于重复字段进行处理,避免删除。
def my_xyk(a,b):
    if ('xxxx') in a:
        return a+str(b)
    else:
        return a

def vlookup_sub_find_all(sub_file,all_file):

    df_sub=pd.DataFrame(pd.read_excel(sub_file,converters={'CellName':str,'eNodeBID':str,'ddd':str},sheet_name='达坂城区'))  #读入子表,
    df_sub['序号']=df_sub.index   #取一个不起作用的字段临时记一下自然记录号

    df_sub['CellName']=df_sub.apply(lambda row: my_xyk(row['CellName'],row['序号']),axis=1) #XYK开头的流水号会不唯一,形成笛卡儿积,为了不让‘XYK’开头的流水号被去重。


    df_sub['is_duplicated'] = df_sub.duplicated(['CellName'])
    df_dup = df_sub.loc[df_sub['is_duplicated'] == True]
    print(df_dup)
    print(df_sub['CellName'])

    df_sub.drop_duplicates('CellName','first',inplace=True)  #去重
    df_all=pd.DataFrame(pd.read_excel(all_file,sheet_name='总表'))  #读入主表,含有【用途】字段
    df_all.drop_duplicates('CellName','first',inplace=True)  #去重
    df=pd.merge(df_all.loc[:,['CellName','Longitude','Latitude']],df_sub,how='right',on='CellName')   #,sort=False不用以on键排序,生成了追加【用途】的子表数据df1.loc[:,['CellName','Longitude','Latitude']],df2,on="CellName",how="right",)
    #print(df)
    df['Longitude'].fillna(df['eNodeBID']+'(自补)',axis=0,inplace=True) #清洗需要用得的空数据,列方向
    return  df

sub_file=all_file='E:\python_project\hhh.xlsx'
ss=vlookup_sub_find_all(sub_file,all_file)
print(ss)

在这里插入图片描述

代码解释:
df1 = pd.read_excel(‘hhh.xlsx’,sheet_name=‘总表’)读取sheet名为 总表 名的sheet;
db1 =df1[“CellName”].duplicated().value_counts() 查看表中名为cellname字段是否有重复
df_sub.drop_duplicates() 删除表中重复。
df[‘Longitude’].fillna(df[‘eNodeBID’]+’(自补)’,axis=0,inplace=True) 没有vlookup到的用enbid和自补填充。

本次的问题是 判断重复用的字段,未找到合适方法。
参照:https://blog.csdn.net/weixin_43097265/article/details/102910597

df1 = pd.read_excel('hhh.xlsx',sheet_name='总表')
df2 = pd.read_excel('hhh.xlsx',sheet_name='达坂城区')
db1 =df1["CellName"].duplicated().value_counts()
db2 =df2["CellName"].duplicated().value_counts()


df_V = pd.merge(df1.loc[:,['CellName','Longitude','Latitude']],df2,on="CellName",how="right",)
print(df_V)
data = df1.head() #默认读取前5行
print("获取前5行值:\n{0}",format(data))
ss = df_V.query('Longitude == ["NaN"]')
print("未匹配:\n{0}",format(ss))

在这里插入图片描述

发布了6 篇原创文章 · 获赞 0 · 访问量 849

猜你喜欢

转载自blog.csdn.net/weixin_41068323/article/details/105778609
今日推荐