在一个数据框中,我有两个列,其中包含一些足球运动员首次登场的时间信息。这些列被称为“首次登场”和“首次登场”。我必须创建一个函数来创建一个新列,其中包含两列的YYYY年信息,并在应用时保留两列的Nan值。让我展示并举例:
使用到目前为止我编写的代码,我能够从一列中获取值,并将其放入新的列中,但我从未达到将这两个列组合在一起的形式
结果应该是这样的:
你能帮我把这个密码弄对吗
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```
我建议您使用str.extract+combine_first
输出
有关如何在pandas中使用字符串的详细信息,请参见this
更新
如果需要列为数字,可以执行以下操作:
请注意,由于列中缺少值,因此不能为int32类型。它可以是nullable integer或浮动。有关处理缺失数据的更多信息,请参见this
相关问题 更多 >
编程相关推荐