Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 通过在Python中组合具有相同索引的值来创建新列?_Python 3.x_Pandas - Fatal编程技术网

Python 3.x 通过在Python中组合具有相同索引的值来创建新列?

Python 3.x 通过在Python中组合具有相同索引的值来创建新列?,python-3.x,pandas,Python 3.x,Pandas,我试图通过groupby现有列和join其值来创建一个新列 例如,原始数据帧(df)如下所示: index col1 col2 col3 0 bar tic A 1 bar tac B 2 far toe C 3 far toe D 然后,如果col1和col2完全匹配,我想将col3中的值与“-”连接起来创建col4。 所需格式为: index col1 col2 col3 col4 0 bar tic

我试图通过
groupby
现有列和
join
其值来创建一个新列

例如,原始数据帧(df)如下所示:

index  col1 col2 col3
0      bar   tic   A
1      bar   tac   B
2      far   toe   C
3      far   toe   D
然后,如果
col1
col2
完全匹配,我想将
col3
中的值与“-”连接起来创建col4。
所需格式为:

index  col1 col2 col3 col4
0      bar  tic    A    A
1      bar  tac    B    B
2      far  toe    C   C-D
3      far  toe    D   C-D
我使用了下面的代码,但没有得到预期的结果,并收到警告消息“UserWarning:Pandas不允许通过新属性名创建列” 我该怎么办

import pandas as pd

df.col4 = df.groupby(['col1', 'col2'])['col3'].apply(lambda x: '-'.join(x))
df.drop_duplicates() 

使用
GroupBy.transform

df['col4'] = df.groupby(['col1', 'col2'])['col3'].transform('-'.join)

  col1 col2 col3 col4
0  bar  tic    A    A
1  bar  tac    B    B
2  far  toe    C  C-D
3  far  toe    D  C-D

如果要聚合行,请使用
GroupBy.apply
链接
reset\u index

df.groupby(['col1', 'col2'])['col3'].agg('-'.join).reset_index()

  col1 col2 col3
0  bar  tac    B
1  bar  tic    A
2  far  toe  C-D

使用
GroupBy.transform

df['col4'] = df.groupby(['col1', 'col2'])['col3'].transform('-'.join)

  col1 col2 col3 col4
0  bar  tic    A    A
1  bar  tac    B    B
2  far  toe    C  C-D
3  far  toe    D  C-D

如果要聚合行,请使用
GroupBy.apply
链接
reset\u index

df.groupby(['col1', 'col2'])['col3'].agg('-'.join).reset_index()

  col1 col2 col3
0  bar  tac    B
1  bar  tic    A
2  far  toe  C-D