[英]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.我想向 A 添加一个新列,称为“B”,其值取决于索引。 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.这意味着如果索引元素在 A 和 B 上共享,则应添加 B 的该行(对应于该索引)的值。 Otherwise 0. The result should look like this否则为 0。结果应该是这样的
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?如何在 Python/pandas 中有效地实现这一点?
reindex
with assign reindex
分配
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.