我正在创建一个数据帧
import pandas as pd
df1 = pd.DataFrame( {
"Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] ,
"City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle",
"Portland"] } )
df1.groupby( ["City"] )['Name'].transform(lambda x:
','.join(x)).drop_duplicates()
I want the output as
Name City
Alice,Bob,Mallory,Bob Seattle
Mallory,Mallory Portland
but i am getting only
Name
Alice,Bob,Mallory,Bob
Mallory,Mallory
This is an example with small number of columns but in my actual problem i
have too many columns so i cannot use
df1['Name']= df1.groupby( ['City'] )['Name'].transform(lambda x:
','.join(x))
df1.groupby( ['City','Name'], as_index=False )
df1.drop_duplicates()
因为对于每一列,我必须编写相同的代码
有没有办法不为每一列编写转换
个别地。在
你可以的
或者
^{pr2}$对于多个聚合
1。列聚合
我认为您需要^{} 和
,.join
,然后对于变更单,使用双[[]]
:因为^{} 使用聚合值创建新列:
^{pr2}$2。列和更多聚合
如果更多的列需要在} 或不指定join all string列:
[]
中使用指定列的^{如果需要,聚合所有列:
相关问题 更多 >
编程相关推荐