我目前有一个像这样的数据框 (df):
name info
alpha foo,bar
alpha bar,foo
beta foo,bar
beta bar,foo
beta baz,qux
我正在寻找创建这样的数据框:
name info
alpha (foo,bar),(bar,foo)
beta (foo,bar),(bar,foo),(baz,qux)
我正在接近 groupby.apply(list)。例如。
new_df=df.groupby('name')['info'].apply(list)
但是,我似乎无法弄清楚如何以原始数据帧格式获取输出。 (即有两列(如示例)
我想我需要 reset_index 和 unstack?感谢任何帮助!
请您参考如下方法:
尝试使用 for 循环执行以下操作:
uniqnames = df.name.unique() # get unique names
newdata = [] # data list for output dataframe
for u in uniqnames: # for each unique name
subdf = df[df.name == u] # get rows with this unique name
s = ""
for i in subdf['info']:
s += "("+i+")," # join all info cells for that name
newdata.append([u, s[:-1]]) # remove trailing comma from infos & add row to data list
newdf = pd.DataFrame(data=newdata, columns=['name','info'])
print(newdf)
输出完全符合要求:
name info
0 alpha (foo,bar),(bar,foo)
1 beta (foo,bar),(bar,foo),(baz,qux)
