找出两列表的共有元素python_python 找出两个dataframe中不同的元素
pandas從Excel中讀取數據,數據格式為dataframe格式
用for循環對進行兩個列的數據比較想找出不同的元素時,發現數據是一樣的,但是比較結果卻是相同和不同的都存在(總之就是不是我以為的效果)
后來將要對比的兩列數據先轉成list再對比,得出理想結果(反思老感覺很簡單的功能寫了一大堆),如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
####test1.xlsx的item列,將會和test.xlsx的Item列數據進行對比
df1 = pd.read_excel('test1.xlsx')
dfItem_Old = df1['item']
####test表的Item列
df = pd.read_excel('test.xlsx')
dfItem_New = df['Item']
dfCommand_New = df['Command']
dfValue_New = df['Value']
dfAutotest = df['Autotest']
dfProgress = df['Progress']
#####將要對比的兩個dataframe格式數據先轉為list
dfItem_New = dfItem_New.tolist()
dfItem_Old = dfItem_Old.tolist()
####找出在dfItem_New列表中但是不在dfItem_Old列表中的元素
differentKey = [x for x in dfItem_New if x not in dfItem_Old]
#print(differentKey)
####test.xlsx中需要的關鍵數據保存在字典中
dict_new = {'item':dfItem_New, 'autotest':dfAutotest, 'command':dfCommand_New, 'value':dfValue_New, 'progress':dfProgress}
####將differentKey不同的元素和字典中的item列作對比,如果存在的話就刪除,且同時將其他列的此行一并刪除(否則會出現行數不一致,報錯)
for i in differentKey:
if i in dict_new['item']:
####找出不同元素的下標,
index = dict_new['item'].index(i)
#print(index)
dict_new['item'].pop(index)
dict_new['autotest'].pop(index)
dict_new['command'].pop(index)
dict_new['value'].pop(index)
dict_new['progress'].pop(index)
#else:
#print(i)
####將刪除后的數據重組
Item = dict_new['item']
Autotest = dict_new['autotest']
Command = dict_new['command']
Value = dict_new['value']
Progress = dict_new['progress']
dict = {'Item':Item, 'Autotest':Autotest, 'Command':Command, 'Value':Value, "Progress":Progress}
總結
以上是生活随笔為你收集整理的找出两列表的共有元素python_python 找出两个dataframe中不同的元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ajax 微信code获取_ajax 实
- 下一篇: virtualbox配置apache_V