hoomant
hoomant

Reputation: 455

Merge multiple Series as a single column into a DataFrame

I have the following data frames:

A.

   k  m  n
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x
5  x  x  x
6  x  x  x
7  x  x  x
8  x  x  x
9  x  x  x

B1.

   l   i  j
1  x  46  x
2  x  64  x
3  x  83  x
9  x  70  x

B2.

   l   i  j
0  x  23  x
4  x  34  x
6  x  54  x
8  x  32  x

B3.

   l   i  j
0  x  11  x
5  x  98  x
7  x  94  x
9  x  80  x

How can I add the column "i" (from data frames B1, B2, and B3) to the data frame A?

Regarding the duplicate values (e.g. index 9 in B1 and B3 & index 0 in B2 and B3), I want to keep the leftmost value from [B1, B2, B3] (e.g. 23 for index 0 & 70 for index 9).

A desired output would be:

   k  m  n   i
0  x  x  x  23
1  x  x  x  46
2  x  x  x  64
3  x  x  x  83
4  x  x  x  34
5  x  x  x  98
6  x  x  x  54
7  x  x  x  94
8  x  x  x  32
9  x  x  x  70

Upvotes: 0

Views: 92

Answers (1)

Ben.T
Ben.T

Reputation: 29635

you can concat the Bx dataframes, and use duplicated on the index to remove the duplicated index and keep the first.

A['i'] = (pd.concat([B1, B2, B3])
            .loc[lambda x: ~x.index.duplicated(keep='first'), 'i'])
print(A)
   k  m  n   i
0  x  x  x  23
1  x  x  x  46
2  x  x  x  64
3  x  x  x  83
4  x  x  x  34
5  x  x  x  98
6  x  x  x  54
7  x  x  x  94
8  x  x  x  32
9  x  x  x  70

Upvotes: 1

Related Questions