简体   繁体   中英

How to assign a certain value into a new column in a pandas dataframe depending on index

Suppose I have two pandas data frames, one actually more like a series

import pandas as pd
import numpy as np
A = pd.DataFrame(index=[0, 1, 2], data=[[1, 2, 3], [4, 5, 6] ,[7,8,9]],columns=["I", "L","P"])
B = pd.DataFrame(index=[1, 3, 4], data=[[10], [40] ,[70]])

I would like to add a new column to A, called "B" with values depending on the index. That means if the index element is shared on both, A and B, then the value of that row (corresponding to that index) of B should be added. Otherwise 0. The result should look like this

A = pd.DataFrame(index=[0, 1, 2], data=[[1, 2, 3,0], [4, 5, 6,10] ,[7,8,9,0]],columns=["I", "L","P","B"])
A

How can this be achieved efficiently in Python / pandas?

reindex with assign

A['B'] = B[0].reindex(A.index,fill_value=0)
A
Out[55]: 
   I  L  P   B
0  1  2  3   0
1  4  5  6  10
2  7  8  9   0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM