我有两列,并希望将值从一列连接到另一列。我想将“ A”列中的值连接到“ B”列中,但是在和处,如果“ B”列中的一个单元格不为空且仅包含值,则我希望每个单元格中的“ B”列都使用两行如果“ B”列中的单元格为空,则从“ A”列开始。
这是数据框
df
A B
Nr.1 18b
Nr.1
Nr.1 18c\nNr.2\n
Nr.1 18d\nNr.1
Nr.2
Nr.2 20a\n
Nr.2 20a\nNr.2
Nr.3 20b\nNr.2\n
Nr.3
所以,在我想要的地方:
df
A B
Nr.1 18b\nNr.1
Nr.1 Nr.1
Nr.1 18c\nNr.1
Nr.1 18d\nNr.1
Nr.2 Nr.2
Nr.2 20a\nNr.2
Nr.2 20a\nNr.2
Nr.3 20b\nNr.2
Nr.3 Nr.3
我尝试使用df ['B'] = df [[“ B”,“ A”]]。apply(lambda x:''.join(x.dropna()。astype(str)),axis = 1)当我想添加“ A”列中的值,并且当“ B”列中的单元格以换行符(\ n)结尾时,它可以工作
当我在字符串末尾没有换行符时,我使用df ['B'] = df [[“ B”,“ A”]]。apply(lambda x:'\ n'.join( x.dropna()。astype(str)),axis = 1)
但是问题是当单元格中已经有两行时。我需要用“ A”列中的值替换第二行中的值,并且字符串的末尾不应为“ \ n”。
解决这个问题有一些优雅的方法吗? 感谢您的帮助。
答案 0 :(得分:1)
# 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']
答案 1 :(得分:1)