首页 > 解决方案 > pandas 遍历列以查找文本匹配,一旦找到,比较两个数据帧中的相邻行值 <>

问题描述

尝试学习在 pandas 中迭代或循环遍历列的方法。在 vba 中,这是一个 for 循环,然后从选定的单元格位置选择偏移量,这只是一个选项。但是,我来这里是为了学习 pandas,并且很难理解如何在将下一列与右侧的邻接或两列进行比较时保持行直。另一种说法可能是这样。在其他数据框 mtype 列中找到 ttype 列文本后,我想将两个数据框中的相邻值相互比较。

我附上了数据框进行测试。我不确定 for 循环是否是实现这一目标的最佳方法,但我已经开始了。我读到 pandas 一次处理整个专栏的效率更高。不确定是否可以在这里完成。我的前 3 行代码(2 个 for 循环和 if 语句)正在工作。它循环遍历文本并找到匹配项。但我正在努力处理邻接值。我已经阅读了 iloc 和 loc 语句,因为我觉得它们抓住了行。但我不确定语法。我什至不确定我是否可以提出正确的问题来让我到达我需要的地方,以便我可以学习。因此,您可以帮助指导我了解这方面的任何阅读材料将不胜感激。pandas loc vs. iloc vs. ix vs. at vs. iat? 根据熊猫数据框中字符串列表的另一列获取列值

需要什么:使用 toc 数据框,我想循环遍历 ttype 列中的每个值,如果 moc 数据框 mtype 列中存在值,则比较 toc[ta column value] < moc[ma column value],如果为真,则继续,如果为假,则 toc[outfilter] == '1'。

import pandas as pd
from pandas import DataFrame, Series
import numpy as np

toc = {'ttype':['ta1k', 'brek', 'sjfgd',
           'gru2d','brek','crhe','ta1k','jump4'],
       'ta':[1, 2, 9, 9, 2, 2, 1, 1],
       'tc':[0, 1, 0, 0, 1, 0, 2, 0],
       'outfilter':[0, 0, 0, 0,0, 0, 0, 0]}

toc = pd.DataFrame(toc)

moc = {'mtype':[ 'sjfgd','ta1k','gru2d',
            'brek','crhe','jump4'],
       'mo':[2, 2, 4, 4, 3, 4],
       'ma':[2, 2, 4, 4, 2, 3],
       'mc':[1, 1, 3, 3, 1, 1]}

moc = pd.DataFrame(moc)

#-----
for tval in toc['ttype']:                          # Gets toc['ttype'].value
    for mval in moc['mtype']:                      # Gets toc['mtype'].value
        if t == m:                                 # compares if tval == mval
            if toc.loc['ta'] < moc.loc['ma']:      # compares toc.[ta] column value < moc.[ma]
                continue
            else:
                toc.loc['outfilter'] = '1'         # if the above is greater place '1' in outfilter 
                                                   #  column
        else:
            continue
#-----
 print(toc)
 print(moc)


 What I would like to do:  The '1's located in the outfilter column are a result of the toc-df[ta 
 column value] being greater than moc-df[ma column value]. 

 toc-df  ttype   ta   tc   outfilter
     0   ta1k    1    0    0
     1   brek    2    1    0
     2   sjfgd   9    0    1
     3   gru2d   9    0    1
     4   brek    2    1    0
     5   crhe    2    0    0
     6   ta1k    1    2    0
     7   jump4   1    0    0

我真的很感谢你们的帮助,我希望有一天我能回报这个人情并把它向前推进。感谢您的时间。!!!如果您有任何问题,请告诉我。

标签: pythonpandas

解决方案


  1. 我将合并ttypemtype列上的数据框,类似于在 Excel 中进行索引匹配/vlookup,但您不想合并整个moc数据框,因此只需指定并合并您需要的列(mtypema)。
  2. 从那里,只需执行一个np.where查看ta值是否大于ma值并返回10类似于 Excelif公式。
  3. 最后,删除不需要的列

输入:

import pandas as pd, numpy as np
toc = {'ttype':['ta1k', 'brek', 'sjfgd',
       'gru2d','brek','crhe','ta1k','jump4'],
   'ta':[1, 2, 9, 9, 2, 2, 1, 1],
   'tc':[0, 1, 0, 0, 1, 0, 2, 0],
   'outfilter':[0, 0, 0, 0,0, 0, 0, 0]}

toc = pd.DataFrame(toc)

moc = {'mtype':[ 'sjfgd','ta1k','gru2d',
        'brek','crhe','jump4'],
   'mo':[2, 2, 4, 4, 3, 4],
   'ma':[2, 2, 4, 4, 2, 3],
   'mc':[1, 1, 3, 3, 1, 1]}

moc = pd.DataFrame(moc)

代码:

toc = pd.merge(toc,moc[['mtype','ma']],how='left',left_on='ttype',right_on='mtype')
toc['outfilter'] = np.where((toc['ta'] > toc['ma']),1,0)
toc = toc.drop(['mtype','ma'], axis=1)
toc

逐行代码分解:

第 1 步(类似于 excelindex-match公式):

pd.merge(toc,moc[['mtype','ma']],how='left',left_on='ttype',right_on='mtype')

   ttype  ta  tc  outfilter  mtype  ma
0   ta1k   1   0          0   ta1k   2
1   brek   2   1          0   brek   4
2  sjfgd   9   0          0  sjfgd   2
3  gru2d   9   0          0  gru2d   4
4   brek   2   1          0   brek   4
5   crhe   2   0          0   crhe   2
6   ta1k   1   2          0   ta1k   2
7  jump4   1   0          0  jump4   3

第 2 步(类似于 excelIF公式):

toc['outfilter'] = np.where((toc['ta'] > toc['ma']),1,0)

    ttype  ta  tc  outfilter  mtype  ma
0   ta1k   1   0          0   ta1k   2
1   brek   2   1          0   brek   4
2  sjfgd   9   0          1  sjfgd   2
3  gru2d   9   0          1  gru2d   4
4   brek   2   1          0   brek   4
5   crhe   2   0          0   crhe   2
6   ta1k   1   2          0   ta1k   2
7  jump4   1   0          0  jump4   3

第 3 步 - 最终输出(只是删除不需要的列):

toc = toc.drop(['mtype','ma'], axis=1)

   ttype  ta  tc  outfilter
0   ta1k   1   0          0
1   brek   2   1          0
2  sjfgd   9   0          1
3  gru2d   9   0          1
4   brek   2   1          0
5   crhe   2   0          0
6   ta1k   1   2          0
7  jump4   1   0          0

如果我想得更多,可能有一种更简单的方法可以在 python 中执行此操作,只需使用 pandas 方法的一行 cod,但这种方法足够简单且易于理解。

此外,VBA 也是我在大约 18 个月前从 Pandas 切换到的语言。我想说 99% 的问题都可以通过 pandas 方法、列表理解或.apply(lambda x:.... Pandas 方法或 numpy 方法在简单性、速度、性能等方面总是要走的路。在 VBA 中循环非常流行,但你应该尽可能快地摆脱它,并学习各种 pandas方法。


推荐阅读