简体   繁体   English

如何根据索引将某个值分配到 Pandas 数据框中的新列中

[英]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.

相关问题 如何在 pandas dataframe 中为具有字符串条件的新列分配值 - How to assign a value to a new column with a string condition in pandas dataframe 如何将新列分配给 Pandas 中的现有 DataFrame - How to assign new column to existing DataFrame in pandas 如何根据Pandas DataFrame中其他列的值仅对列的某些元素求和? - How to sum only certain elements of a column depending on value of other column in Pandas DataFrame? 根据值是否在某个值范围内,在 DataFrame 中分配新列 - Assign new column in DataFrame based on if value is in a certain value range 在 pandas dataframe 中,如何根据列值过滤行,进行计算并将结果分配给新列? - In a pandas dataframe, how can I filter the rows based on a column value, do calculation and assign the result to a new column? 熊猫:根据另一个数据框分配值 - Pandas: assign value depending on another dataframe 如何根据多索引熊猫数据框中的行索引值创建列? - How to create a column depending on the row index values in a multiindex pandas dataframe? Pandas:如何根据每行包含 json 的列值创建新的 dataframe? - Pandas: how to create a new dataframe depending on a column value containing json for each row? 如何在 Python Pandas DataFrame 中将索引拆分为新索引和新列? - How to split index into new index and new column in Python Pandas DataFrame? Pandas 数据框 - 如何分配索引? - Pandas dataframe - how to assign index?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM