简体   繁体   English

使用基于 ID 列的另一行的值来估算 Pandas 数据框列

[英]Impute Pandas dataframe column with value from another row based on ID column

df:东风:

id   name 
0    toto                    
1    tata
0    NaN

I would like to impute the name column missing value on the third row based on the id.我想根据 id 在第三行估算名称列缺失值。 The desired dataframe would be:所需的数据框将是:

id   name 
0    toto                    
1    tata
0    toto

I did the following:我做了以下事情:

df.loc[df.name.isna(), "name"] = df["id"].map(df["name"])

but it is not working.但它不工作。

import pandas as pd
df = pd.DataFrame({'id':[0,1,0],
              'name':['toto','tata',pd.NA]})

df = df[['id']].merge(df[pd.notna(df['name'])].drop_duplicates(),
                      how = 'left', 
                      on = 'id')
df

If there is only one value exists in the group, you can try如果组中只存在一个值,您可以尝试

df = df.groupby('id').apply(lambda g: g.ffill().bfill())
print(df)

   name
0  toto
1  tata
2  toto

Or sort NaN to the last或者将NaN排序到最后

df = (df.sort_values('name')
      .groupby('id').ffill()
      .sort_index())

暂无
暂无

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

相关问题 根据 Pandas 中的 id 将列值从一个数据帧复制到另一个数据帧 - Copy column value from one dataframe to another based on id in Pandas pandas 根据条件将列添加到 dataframe 具有来自另一行的值 - pandas add column to dataframe having the value from another row based on condition 根据熊猫中的行匹配,用另一个DataFrame中的值有条件地填充列 - Conditionally fill column with value from another DataFrame based on row match in Pandas 根据熊猫列中的值从DataFrame中选择特定的行 - Select particular row from a DataFrame based on value in a column in pandas 根据列值删除Pandas中的DataFrame行 - Deleting DataFrame row in Pandas based on column value 如何根据 ID 和指向 df2 中列名称的值从另一个 dataframe (df2) 中的列中获取值。 蟒蛇/熊猫 - How to get a value from a column in another dataframe (df2), based on ID and on a value that points to the name of the column in df2. Python/Pandas 如何根据 Row_id 列将值写入 dataframe 的另一列并且匹配列中存在值? - How to write the values to another column of dataframe based on Row_id column and value exist in match column? 根据另一列中的条件从 Pandas 数据框中提取值 - Extract Value From Pandas Dataframe Based On Condition in Another Column 通过基于另一列的模式估算列值 - Impute column value via mode based on another column Pandas Dataframe:对于给定的行,尝试基于在另一列中查找值来分配特定列中的值 - Pandas Dataframe: for a given row, trying to assign value in a certain column based on a lookup of a value in another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM