pandas 用其他列的值填充列中的空单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36942453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:08:47  来源:igfitidea点击:

Fill empty cells in column with value of other columns

pythonpandasna

提问by alpenmilch411

I have a HC list in which every entry should have an ID, but some entries do not have an ID. I would like to fill those empty cells by combining the the first name column and the last name column. How would I go about this? I tried googling for fillna and the like but couldn't get it to work. What I want is basically this:

我有一个 HC 列表,其中每个条目都应该有一个 ID,但有些条目没有 ID。我想通过组合名字列和姓氏列来填充这些空单元格。我该怎么办?我尝试在谷歌上搜索 fillna 之类的东西,但无法让它工作。我想要的基本上是这样的:

If hc["ID"] == "": 
    hc["ID"] = hc["First Name"] + hc["Last Name"]

回答by EdChum

You can use locand a boolean mask if NaNthen:

如果这样,您可以使用loc和布尔掩码NaN

hc.loc[hc["ID"].isnull(),'ID'] = hc["First Name"] + hc["Last Name"] 

otherwise for empty string:

否则对于空字符串:

hc.loc[hc["ID"] == '','ID'] = hc["First Name"] + hc["Last Name"]

回答by Diedrich

As an alternative, you can also use fillna() if not dealing with strings:

作为替代方案,如果不处理字符串,您也可以使用 fillna():

hc['ID'].fillna(hc['First Name'] + hc['Last Name'], inplace=True)

hc['ID'].fillna(hc['First Name'] + hc['Last Name'], inplace=True)

docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html

文档:https: //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html

Cheers

干杯