[英]Altering values from a pandas DataFrame slice using different DataFrames
I want to assign values to a column of a pandas DataFrame using a slice from other DataFrame that have commom indexes. 我想使用来自其他具有通用索引的DataFrame的切片将值分配给Pandas DataFrame的列。 More or less like create a new column in a df1 filling the values from another DataFrame column (in the following example, df2['D']) that have the same index.
或多或少像在df1中创建一个新列,以填充另一个DataFrame列(在以下示例中为df2 ['D'])中具有相同索引的值。
Example: I have two DataFrames, df1 and df2. 示例:我有两个DataFrame,即df1和df2。
df1
A B
g
a 0.286074 0.148268
b 0.271671 0.356847
c 0.155908 0.951075
df2
C D
g
c 0.218612 0.296498
d 0.382499 0.900638
Now I want to add a new column to df1 with all values from df2['D'] that have the same index (row) in df1. 现在,我要向df1中添加新列,其中df2 ['D']中的所有值在df1中具有相同的索引(行)。 I know that I can do something like this:
我知道我可以做这样的事情:
for g in df2.index:
if g in df1.index.values.tolist():
df1.loc[g, 'D'] = df2.loc[g, 'D']
df1
A B D
g
a 0.286074 0.148268 NaN
b 0.271671 0.356847 NaN
c 0.155908 0.951075 0.296498
and works fine! 并且工作正常! But I think the solution is so ugly and is not using the power of pandas DataFrame at all.
但是我认为该解决方案非常丑陋,根本没有使用pandas DataFrame的功能。
I've tried to do something like the following, but did not work at all: 我试图做类似以下的事情,但是根本没有用:
df1.reindex(df1.index.intersection(df2.index))['D'] = df2['D']
df1
A B
g
a 0.286074 0.148268
b 0.271671 0.356847
c 0.155908 0.951075
I've tried to do a bunch of other things using loc or queries, but none of them work. 我已经尝试使用loc或query做很多其他事情,但是它们都不起作用。
This example was created based on what I need to do with tables containing large heavy data, this is why I want to optimize the result. 此示例是根据我需要处理包含大量数据的表而创建的,这就是为什么我要优化结果的原因。
Thanks in advance! 提前致谢!
Just assign it 只需分配它
df1['D']=df2.D
df1
A B D
a 0.286074 0.148268 NaN
b 0.271671 0.356847 NaN
c 0.155908 0.951075 0.296498
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.