Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.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 在Groupby上填写nan并跨行连接名称_Python_Pandas - Fatal编程技术网

Python 在Groupby上填写nan并跨行连接名称

Python 在Groupby上填写nan并跨行连接名称,python,pandas,Python,Pandas,假设我有这样的数据帧: df = pd.DataFrame([['US123','Brown, Alan'],['CA456', 'Powell, Jared'], ['US123', np.nan],['US123','Rebecca, Julia'], ['CA456', 'Mike, Joe']], columns=['ID', 'Name']) df 我希望得到如下结果: 我怎样才能做到这一点?谢谢大家! 使用: df.groupby('ID', as_index=False)[[

假设我有这样的数据帧:

df = pd.DataFrame([['US123','Brown, Alan'],['CA456', 'Powell, Jared'], ['US123', np.nan],['US123','Rebecca, Julia'], ['CA456', 'Mike, Joe']], columns=['ID', 'Name'])
df

我希望得到如下结果:

我怎样才能做到这一点?谢谢大家!

使用:

df.groupby('ID', as_index=False)[['Name']].agg(lambda x: '; '.join(x.dropna()))
输出:

      ID                         Name
0  CA456     Powell, Jared; Mike, Joe
1  US123  Brown, Alan; Rebecca, Julia

另一种方法是将ID设置为索引,并使用
stack
这将默认删除任何NA行

df.set_index('ID').stack().groupby(level=0).agg(names=';'.join).reset_index()

      ID                       names
0  CA456     Powell, Jared;Mike, Joe
1  US123  Brown, Alan;Rebecca, Julia

尝试
df.groupby('ID')['Name'].agg(':'.join)
Well。。因为对于NaN,请尝试
df.groupby('ID')['Name'].agg(lambda x:';'.join(x.dropna())
在加入之前删除空值可能会更快?只是一个很好用的想法!非常感谢你!我实际上在做一些疯狂的事情——定义一个函数,然后将它应用到Groupby对象。但这要容易得多!