合并相同的列名数据并使其成为单个数据框的单个数据

问题描述 投票:0回答:2

我的数据框 ABC 中有以下几列。

  • 用户标签
  • 用户标签

两者同名

我需要将两者合并并将其作为单列用户标签。 例如,如果我有以下数据

userLabel = ['a', '', 3, '', 'b']
userLabel = ['', '2', '', '4', '']

我需要像下面这样的

userLabel = ['a', 2, 3, 4, 'b']

我尝试了下面的代码,但没有成功

   ABC['userLabel'] = ABC['userLabel'].fillna(ABC['userLabel'])
python-3.x pandas dataframe
2个回答
0
投票

假设这样的输入:

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

0
投票

用途:

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
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.