简体   繁体   English

如何将 append 列转换为 DataFrame 以收集 Python 中另一个 DataFrame 的值?

[英]How to append a column to a DataFrame that collects values of another DataFrame in Python?

I have two tables (as Pandas' DataFrame), one is like我有两个表(作为 Pandas 的 DataFrame),一个就像

name姓名 val
name1姓名1 0 0
name2名字2 1 1个

the other is另一个是

name姓名 tag标签
name1姓名1 tg1 tg1
name1姓名1 tg2 tg2
name1姓名1 tg3 tg3
name1姓名1 tg3 tg3
name2名字2 kg1公斤1
name2名字2 kg1公斤1
name3名字3 other其他

and I want to append a column to the first DataFrame collecting all values of the second table by name, ie我想 append 一列到第一个 DataFrame 按名称收集第二个表的所有值,即

name姓名 val new_column新专栏
name1姓名1 0 0 [tg1, tg2, tg3, tg3] [tg1, tg2, tg3, tg3]
name2名字2 1 1个 [kg1, kg1] [kg1, kg1]

I know I can use row-wise operation to achieve this, but is there a way that I can use inbuilt Pandas' methods to do this?我知道我可以使用逐行操作来实现这一点,但是有没有一种方法可以使用内置的 Pandas 方法来做到这一点? If I want to remove duplicates of the collected array in new_column at the same time, what method should I use?如果我想同时去除new_column中collected数组的重复项,应该用什么方法呢?

Use DataFrame.join with aggregate list s:DataFrame.join与聚合list一起使用:

df = df1.join(df2.groupby('name')['tag'].agg(list).rename('new_column'), on='name')
print (df)
    name  val            new_column
0  name1    0  [tg1, tg2, tg3, tg3]
1  name2    1            [kg1, kg1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将一个数据帧的列值附加到另一个数据帧的列 - How to append column values of one dataframe to column of another dataframe 将数据框附加到另一个数据框的列和Python常量 - Append a dataframe with a column of another dataframe and a constant with Python 如何将 append 一个 dataframe 变成另一个 dataframe 作为一列 - How to append one dataframe into another dataframe as a column pandas数据框根据另一数据框中的值将值追加到一列 - pandas dataframe append values to one column based on the values in another dataframe 熊猫将数据框附加到另一个不合并列值 - Pandas append dataframe to another not merging column values 如何遍历数据框,创建新列并在python中为其添加值 - How to loop through a dataframe, create a new column and append values to it in python 如何从一个数据框中的列中提取特定值并将它们附加到另一个数据框中的列中? - 熊猫 - How do you extract specific values from a column in one dataframe and append them to a column in another dataframe? - Pandas Python Pandas:仅当列值唯一时,才将数据框追加到另一个数据框 - Python Pandas: Append Dataframe To Another Dataframe Only If Column Value is Unique Python Dataframe:根据另一个数据帧更新数据框中列的值 - Python Dataframe : Update the values of a column in a dataframe based on another dataframe append 列的值基于 dataframe 中另一列的值 - append column with values based on values of another column in the dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM