数据框和concat结果中的值匹配

时间:2018-02-16 20:38:46

标签: python pandas

我有两个数据框,我希望将df1的column1中的条目与df2的第1列和第3列中的条目进行匹配。如果所有三个条目都匹配,则从输出文件中的两个数据帧打印行。例如:

df1:
    a21 1  2  3
    a32 4  5  6
    a43 7  8  9
df2:
    b21 10 21 
    b21 10 22
    b43 10 43

output:
    21  1  2  3  10
    43  7  8  9  10

我目前正在执行以下操作并使用str.extract获取整数:

import pandas as pd
import re

df1 = pd.read_table('data1.txt', delim_whitespace= True)
df1.columns = ['1','2','3','4']
num = df1['1'].str.extract('(\d+)').astype(int)

df2 = pd.read_table('data2.txt', delim_whitespace= True)
df2.columns = ['1','2','3']
num2 = df2['1'].str.extract('(\d+)').astype(int)

both = [df1, df2]
if num == num2:
   if num == df2['3']:
      result = pd.concat(both, axis=1)
      print(result)

我不确定如何匹配这三个值并连接数据帧。我应该创建词典吗? 有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

这是一种方式。

import pandas as pd

df1 = pd.DataFrame([['a21', 1, 2, 3],
                    ['a32', 4, 5, 6],
                    ['a43', 7, 8, 9]],
                   columns=['1', '2', '3', '4'])

df2 = pd.DataFrame([['b21', 10, 21],
                    ['b21', 10, 22],
                    ['b43', 10, 43]],
                   columns=['1', '2', '3'])

df1.index = df1['1'].apply(lambda x: int(x[1:]))
df2.index = df2['1'].apply(lambda x: int(x[1:]))

# filter df2 for where index = column 3
df3 = df2[df2.index == df2['3']]

# join onto df1
df4 = df1.merge(df3, left_index=True, right_index=True).drop(['1_x', '1_y'], 1)

#     2_x  3_x  4  2_y  3_y
# 1                        
# 21    1    2  3   10   21
# 43    7    8  9   10   43
相关问题