从两个字符串列中提取YYYY年,并将其放入新列中,保留NaN值

2024-09-28 21:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个数据框中,我有两个列,其中包含一些足球运动员首次登场的时间信息。这些列被称为“首次登场”和“首次登场”。我必须创建一个函数来创建一个新列,其中包含两列的YYYY年信息,并在应用时保留两列的Nan值。让我展示并举例:enter image description here

使用到目前为止我编写的代码,我能够从一列中获取值,并将其放入新的列中,但我从未达到将这两个列组合在一起的形式

结果应该是这样的:

^{tb1}$

你能帮我把这个密码弄对吗

    df_4['Debut deportivo'].fillna('0000',inplace=True)
    df_4['Debut'].fillna('0000', inplace=True)
    def find_year(x):
        año = re.search('\d{4}', x)
        return int(año.group(0)) if año else 0
    df_4['fecha_debut'] = df_4['Debut'].map(find_year)
    df_4['fecha_debut'] = df_4 ['Debut deportivo'].apply(lambda x: np.nan if x.find('2')==-1  else x[x.find('0')-1:x.find('(')])
    df_4['club_debut'] = df_4 ['Debut deportivo'].apply(lambda x: np.nan if x.find ('(')==-1  else x[x.find('(')+1:x.find(')')])
    df_4['fecha_debut'] = df_4['fecha_debut'].replace(0,np.nan)
    # No modifiques las siguientes lineas 
    assert(isinstance(df, pd.DataFrame))
    return df``` 

Tags: 信息truedfifnpnanfindelse
1条回答
网友
1楼 · 发布于 2024-09-28 21:31:50

我建议您使用str.extract+combine_first

df['fecha_debut'] = df['Debut'].str.extract(r'(\d{4})').combine_first(df['Debut Deportivo'].str.extract(r'(\d{4})'))
print(df)

输出

                  Debut                   Debut Deportivo fecha_debut
0    27 de mayo de 2006               2006(UD Vecindario)        2006
1  21 de agosto de 2010  11 de agosto de 2010(Portuguesa)        2010
2  21 de agosto de 2010                               NaN        2010
3                   NaN                               NaN         NaN

有关如何在pandas中使用字符串的详细信息,请参见this

更新

如果需要列为数字,可以执行以下操作:

df['fecha_debut'] = pd.to_numeric(df['fecha_debut']).astype(pd.Int32Dtype())

请注意,由于列中缺少值,因此不能为int32类型。它可以是nullable integer或浮动。有关处理缺失数据的更多信息,请参见this

相关问题 更多 >