简体   繁体   English

Pandas填充空白

[英]Pandas filling blanks

Python 3.9 and Pandas 1.3.4 Python 3.9 和 Pandas 1.3.4

So here's the df:所以这里是df:

1   First name  Last Name
2   Freddie     Mercury
3   John        Lennon
4   David       Bowie
5   
6   Joseph
7               Jovi

I'm trying to fill the blank line (5) with "John Doe" when I concat First name and Last name but I do not want to put a "John Doe" in line 6 or 7 as it has a partial name.当我连接First nameLast name时,我试图用“John Doe”填充空白行 (5),但我不想在第 6 行或第 7 行放置“John Doe”,因为它有部分名称。

So this is my current code:所以这是我当前的代码:

import pandas as pd

df = pd.read_csv('file.csv', dtype=str, header=0)
df['First name'] = df['First name'].str.replace(' ', 'John Doe', regex=True)
df['Last name'] = df['Last name'].str.replace(' ', 'John Doe', regex=True)
df['fullname'] = df['First name'].fillna(" ") + " " + df["Last name"].fillna(" ")


df.to_csv('file.csv', index=False)

This currently produces a fullname column which looks like:这当前会生成一个fullname ,如下所示:

fullname
Freddie Mercury
John Lennon
David Bowie

Joseph
Jovi

This is what I want:这就是我要的:

Freddie Mercury
John Lennon
David Bowie
John Doe
Joseph
Jovi

Try:尝试:

df['fullname'] = (df[['First name', 'Last Name']]
   .fillna('').agg(' '.join, axis=1)        # replace nan with '' and concatenate
   .str.strip()                             # remove leading/trailing spaces
   .replace('', 'John Doe')                 # replace empty name with default
)

Output: Output:

  First name Last Name         fullname
0    Freddie   Mercury  Freddie Mercury
1       John    Lennon      John Lennon
2      David     Bowie      David Bowie
3       None      None         John Doe
4     Joseph      None           Joseph
5        NaN      Jovi             Jovi

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM