简体   繁体   English

如何根据 Python 中的列值将 pandas dataframe 单元格设置为等于?

[英]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 值从df2df1

df1.PosRank=df1.Name.map(d)

New df1新df1

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查 pandas dataframe 列中的所有值是否相等? - How do I check if all values in a column of a pandas dataframe are equal? 如何在 Pandas DataFrame 列中设置值等于基于另一个 DataFrame 的值 - How to set values in a Pandas DataFrame Column equal to values based on another DataFrame 在 Pandas Python Dataframe 我需要根据其他列的值设置列的值 - IN Pandas Python Dataframe I need to set values of a column based on the values of other columns 如何基于另一列的NaN值设置熊猫数据框中的值? - How set values in pandas dataframe based on NaN values of another column? 如何根据 Pandas 中的行和列值突出显示单元格? - How can I highlight cells based on row and column values in Pandas? 如何根据另一列的日期条件获取熊猫数据框中特定列的值? - How do I get the values of a particular column in a pandas dataframe based on a date condition on another column? 如何根据条件替换 Panda 数据框列中的单元格 - How do I replace cells in a Panda dataframe column based on a condition 如何将列表值与不完全相等的数据框列进行比较? - How do I compare list values to a dataframe column that are not exactly equal? 根据两列值相等,将列中的字段设置为 0 Pandas - Set Field in Column to 0 Based on Two Column Values Being Equal Pandas 如何根据 Python 中的条件更改 pandas DataFrame 列中的值 - How to change values in a pandas DataFrame column based on a condition in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM