假设我们在两个数据框中有两列,列相同但大小不同。我们如何比较两列并在两列中具有相同值的索引? df1 和 df2,年龄在两个中很常见,但 df1 有 1000 行,df2 有 200 行 - 我想要具有相同年龄值的行的索引?
最佳答案
您可以使用.loc
进行索引标签:
df1.age < df2.loc[df1.index].age
示例:
df1 = pd.DataFrame({'age':np.random.randint(1,10,10)})
df2 = pd.DataFrame({'age':np.random.randint(1,10,20)})
输出:
0 True
1 True
2 False
3 True
4 True
5 False
6 False
7 True
8 False
9 False
Name: age, dtype: bool
将所有内容都集中在一个数据框中:
df1.assign(age_2=df2.loc[df1.index],cond=df1.age < df2.loc[df1.index].age)
输出:
age age_2 cond
0 3 5 True
1 3 8 True
2 6 6 False
3 4 7 True
4 4 7 True
5 5 2 False
6 2 2 False
7 3 7 True
8 6 3 False
9 5 4 False
关于pandas 比较两列不同大小的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45020102/