【发布时间】:2020-07-28 04:29:03
【问题描述】:
尝试学习迭代或循环遍历 pandas 中的列的方法。在 vba 中,这是一个 for 循环,然后从选定的单元格位置选择偏移量,这只是一个选项。但是,我来这里是为了学习 pandas,并且很难理解如何在将下一列与右侧的邻接或两列进行比较时保持行直。另一种说法可能是这样。在其他数据框 mtype 列中找到 ttype 列文本后,我想将两个数据框中的相邻值相互比较。
我已附上数据框进行测试。我不确定 for 循环是否是实现这一目标的最佳方法,但我已经开始了。我读到 pandas 一次处理整个专栏的效率更高。不确定是否可以在这里完成。我的前 3 行代码(2 个 for 循环和 if 语句)正在工作。它循环遍历文本并找到匹配项。但我正在努力处理邻接值。我已经阅读了 iloc 和 loc 语句,因为我觉得它们抓住了行。但我不确定语法。我什至不确定我是否可以提出正确的问题来让我到达我需要的地方,以便我可以学习。因此,您可以帮助指导我了解这方面的任何阅读材料将不胜感激。 pandas loc vs. iloc vs. ix vs. at vs. iat? get column value based on another column with list of strings in pandas dataframe
需要什么:对于 toc 数据框,我想循环遍历 ttype 列中的每个值,如果值存在于 moc 数据框 mtype 列中,则比较 toc[ta column value]
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
我真的很感谢你们的帮助,我希望有一天我能回报这个人情并把它付诸实践。感谢您的时间。!!!如果您有任何问题,请告诉我。
【问题讨论】: