我的数据框 ABC 中有以下几列。
两者同名
我需要将两者合并并将其作为单列用户标签。 例如,如果我有以下数据
userLabel = ['a', '', 3, '', 'b']
userLabel = ['', '2', '', '4', '']
我需要像下面这样的
userLabel = ['a', 2, 3, 4, 'b']
我尝试了下面的代码,但没有成功
ABC['userLabel'] = ABC['userLabel'].fillna(ABC['userLabel'])
假设这样的输入:
df = pd.DataFrame(zip(['a', '', 3, '', 'b'],
['', '2', '', '4', '']),
columns=['userLabel', 'userLabel'])
bfill
并切片:
out = df[['userLabel']].replace('', None).bfill(axis=1).iloc[:, :1]
groupby.first
的变体:
out = df.replace('', None).groupby(axis=1, level=0).first()
在新的 pandas 版本中应该作为转置执行:
out = df.T.replace('', None).groupby(level=0).first().T
输出:
userLabel
0 a
1 2
2 3
3 4
4 b
用途:
ABC['userLabel'] = ABC['userLabel'].replace('', np.nan).ffill(axis=1).iloc[:, -1]
ABC = ABC.loc[:, ~ABC.columns.duplicated() | (ABC.columns != 'userLabel')]
print (ABC)
userLabel col
0 a 1
1 2 1
2 3 1
3 4 1
4 b 1