[英]How do I set pandas dataframe cells equal to based on column values in Python?
Here is my issue, I have two pandas dataframes, all with the same column names, and the same number of rows.这是我的问题,我有两个 pandas 数据帧,都具有相同的列名和相同的行数。 Below is a sample of what each dataframe would look like.
下面是每个 dataframe 的外观示例。 Pandas Dataframe Example
Pandas Dataframe 示例
Let me call my dataframes DF1 and DF2.让我将我的数据框称为 DF1 和 DF2。 I need to take the "PosRank" value from DF1 and set it equal to the "PosRank" of DF2 at the row where the "names" are the same.
我需要从 DF1 中获取“PosRank”值并将其设置为等于“名称”相同行的 DF2 的“PosRank”。 There is no guarantee they will be in any sorted or matching order but all names in DF1 will also be in DF2 and visa versa, and will only appear once in each.
不能保证它们将按任何排序或匹配顺序,但 DF1 中的所有名称也将在 DF2 中,反之亦然,并且每个名称仅出现一次。
There are many ways of doing it.有很多方法可以做到这一点。 Pay attention to the links in comment
注意评论中的链接
Lets try this one where we use Series.map() method.让我们试试这个我们使用Series.map()方法的地方。
df1=pd.DataFrame({'Name':['DeAngelo William','Michael Turner'],'PosRank':[1.0,2.0]})
df1 df1
df2=pd.DataFrame({'Name':['DeAngelo William','Michael Turner'],'PosRank':[3.0,6.0]})
df2 df2
Let us create a dictionary with Name
from df2
as key and PosRank
from df2
as value让我们创建一个字典,其中
df2
中的Name
作为键, df2
中的PosRank
作为值
d=dict(zip(df2.Name,df2.PosRank))
Now map values from df2
to df1
现在 map 值从
df2
到df1
df1.PosRank=df1.Name.map(d)
New df1新df1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.