2 回答
TA贡献1111条经验 获得超0个赞
# 1 - you split column B and keep only the first part
df["B"] = df["B"].str.split(pat='\\', expand=True)[0]
# 2 - you concatenate the 2 columns separated with a \n
df["B"] = df.B + '\n' + df.A
# 3 - the second step didn't work when columns B is empty, so you use loc to replace the NaN with the value of column A
df.loc[df.B.isna(), 'B'] = df.loc[df.B.isna(), 'A']
TA贡献1795条经验 获得超7个赞
split与索引一起使用以选择列表的第一个值,添加分隔符和列A,最后通过fillna以下方式替换缺失值:
df['B'] = (df['B'].str.split('\\').str[0] + '\\n' + df['A']).fillna(df['A'])
print (df)
A B
0 Nr.1 18b\nNr.1
1 Nr.1 Nr.1
2 Nr.1 18c\nNr.1
3 Nr.1 18d\nNr.1
4 Nr.2 Nr.2
5 Nr.2 20a\nNr.2
6 Nr.2 20a\nNr.2
7 Nr.3 20b\nNr.3
8 Nr.3 Nr.3
添加回答
举报