简体   繁体   English

迭代数据框中的每个列,将每个值与另一个数据框中的另一列中的值匹配

[英]Iterate over a column in a dataframe matching each value with a value in another column in another dataframe

I basically have two data frames. 我基本上有两个数据框。 Let's say aa and bb. 假设是aa和bb。 I want to look all the values in the first column of bb that are in the first column of aa and if they are I have to get column 2 of aa and add it to a new column in bb (if there is not much I'll put a 0). 我想查看aa第一列中bb的第一列中的所有值,如果是,则必须获取aa的第二列并将其添加到bb中的新列中(如果我没有太多, ll放一个0)。 Let's see if looking at some code it makes more sense. 让我们看看看一些代码是否更有意义。 I've done it using apply and a function: 我已经使用apply和一个函数完成了它:

aa=pd.DataFrame({'a':[1,2,3,4,5],'b':[6,7,8,9,0]})
bb=pd.DataFrame({'c':[11,2,13,4,15],'d':['f','h','j','k','l']})

   a  b
0  1  6
1  2  7
2  3  8
3  4  9
4  5  0

    c  d
0  11  f
1   2  h
2  13  j
3   4  k
4  15  l


def set_time_session (row):
    element = row['c']
    if element in aa['a'].unique():
        return aa['b'][aa['a']==element]
    else:
        return 0

column = bb.apply(set_time_session,axis=1)
bb['newcolumn']=column

       c  d  newcolumn
0  11  f          0
1   2  h          7
2  13  j          0
3   4  k          9
4  15  l          0

This actually works, but when done in a dataframe with 200000 rows it takes forever to complete. 这实际上是可行的,但是在具有200000行的数据帧中完成时,将永远需要完成。 I'm sure the is a better and faster way to do it. 我敢肯定,这是一种更好更快的方法。 Thanks! 谢谢!

Try this: 尝试这个:

res = pd.merge(aa, bb, left_on='a', right_on='c', how='inner', left_index=True)
bb['newcolumn']= res.reindex(range(len(aa))).fillna(0)['b']
print(bb)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用另一个列的每个值迭代数据框的一行的值 - iterate a value of a row of a dataframe with each value of a column in another 如何迭代每一行并从一个 dataframe 的特定列中找到下一个匹配列值并将其与另一个 dataframe 进行比较? - How to iterate each row and find the next matching column value from a specific column from one dataframe and comparing it to another dataframe? 我想在 dataframe 中迭代,在另一个 dataframe 中添加值(新列) - I want to iterate in dataframe adding value( new column) in another dataframe 基于另一列熊猫数据框迭代列值匹配值 - Iterate over column values matched value based on another column pandas dataframe 如果列中有匹配的值,则使用另一个dataFrame注释一个dataFrame - Annotating one dataFrame using another dataFrame, if there is matching value in column 在列中查找匹配值并创建另一列 pandas dataframe - Find matching value in column and create another column pandas dataframe 如果值在另一个 dataframe 的另一列中,则添加列 - Add column if value is in another column of another dataframe 如何基于另一个列值迭代 Pandas DataFrame 多索引和过滤 - How to iterate over pandas DataFrame multi-index and filtering based off another column value 根据另一个 dataframe 中匹配值的行数创建新列 - Create new column based on number of rows matching value in another dataframe 在未包含在另一个数据帧中的数据框中打印列的值 - Print the value of a column in a dataframe that is not contained in another dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM