在groupby之后使用数据框列连接另一列的值

时间:2019-09-15 16:26:00

标签: python pandas dataframe

我有一个这样的数据框:

import pandas as pd

df = pd.DataFrame(
    {
        'group': list('ABBCA'),
        'values': list('xyztr'),
        'joiner': ['j1', 'j2', 'j2', 'j3', 'j1']
    }
)

  group values joiner
0     A      x     j1
1     B      y     j2
2     B      z     j2
3     C      t     j3
4     A      r     j1

我现在想对列group进行分组,并使用values中的条目将joiner中的各个值连接起来。像这样:

df.groupby('group')['values'].transform(" - ".join)

0    x - r
1    y - z
2    y - z
3        t
4    x - r

只需使用" - "中的相应值代替df['joiner']

我该怎么做?

预期结果将是:

0    x j1 r
1    y j2 z
2    y j2 z
3        t
4    x j1 r

我们可以安全地假设joiner的值与group列一致(否则groupby会失败)。

4 个答案:

答案 0 :(得分:6)

这是一种方法:

core]
logging_conf_file: /etc/luigi/logging.cfg

[scheduler]
record_task_history: True
state-path: /luigi/state/luigi-state.pickle

[task_history]
db_connection: sqlite:////luigi/state/luigi-task-history.db

#!/bin/sh
cat << "EOF"
 _____       __    __    _____      _____     _____
(_   _)      ) )  ( (   (_   _)    / ___ \   (_   _)
  | |       ( (    ) )    | |     / /   \_)    | |
  | |        ) )  ( (     | |    ( (  ____     | |
  | |   __  ( (    ) )    | |    ( ( (__  )    | |
__| |___) )  ) \__/ (    _| |__   \ \__/ /    _| |__
\________/   \______/   /_____(    \____/    /_____(
EOF
echo "Luigi: $LUIGI_VERSION - Python: $(python --version)"

exec luigid

答案 1 :(得分:5)

使用映射器和pd.Series.str.cat

mapper = df.set_index('group').joiner.to_dict()
df.groupby('group').values.transform(lambda s: s.str.cat(sep=f' {mapper[s.name]} '))

  group values joiner  joined
0     A      x     j1  x j1 r
1     B      y     j2  y j2 z
2     B      z     j2  y j2 z
3     C      t     j3       t
4     A      r     j1  x j1 r

答案 2 :(得分:3)

尝试这样的事情:

df.groupby(['group', 'joiner'])['values']\
    .transform(lambda gr: (' ' + gr.name[1] + ' ').join(gr))

答案 3 :(得分:2)

这是另一种方式

s=df.groupby('group').apply(lambda x: (' '+x['joiner'].iloc[0]+ ' ').join(x['values'])).reindex(df.group)
group
A    x j1 r
B    y j2 z
B    y j2 z
C         t
A    x j1 r
dtype: object
df['new']=s.values