其目标是根据多个列组织数据,并将其他列的内容放在一个单元格中,例如,
df:
name type link subs
id
1 x tx 10 sub1
2 x tx 10 sub2
3 y rx 11 sub3
4 y rx 11 sub4
5 y rx 11 sub5 若要根据名称/类型/链接组织表,请期望获得:
name type link subs
id
1 2 x tx 10 sub1 sub2
3 4 5 y rx 11 sub3 sub4 sub5我知道可以基于多个列来组织数据流,
df.groupby(['name','type', 'link']).reset_index()但我不知道如何处理另外两列,然后把它们放在一个牢房里。谢谢你的建议。
发布于 2021-06-25 20:51:49
您可以使用groupby(...)[column].agg(...),因为这是一个简化/聚合。要进行聚合,只需将内容连接到一个字符串中,这样就可以使用类似于" ".join这样的聚合函数,如下所示:
new_df = (
df.reset_index() # we want to operate on the "id" as well
.astype({"id": str}) # " ".join only works on strings, so make "id" string dtype
.groupby(['name','type', 'link'], as_index=False)[["id", "subs"]]
.agg(" ".join)
)
print(new_df)
name type link id subs
0 x tx 10 1 2 sub1 sub2
1 y rx 11 3 4 5 sub3 sub4 sub5注:
将Index
['name', 'type', 'link']分组的列作为列(如果我们没有指定它们将构成as_index=False --此行.groupby(['name','type', 'link'], as_index=False)[["id", "subs"]] ),则不需要指定列,因为它们是数据make中唯一要处理的列。这个片段将在不手动选择它们的情况下运行,我只是更喜欢显式>隐式最后,这些数据主要是有用的。将多个值放入表的单元格中的单个字符串将使这些值在将来很难处理。
要恢复原始数据的排序,可以:
df
"id"设置为索引(正如您最初的数据格式一样),
reindex将new_df的列重新排序为原始的new_df,您可以使用前面的df.columns使用括号符号来选择列
ordered_new_df = new_df.set_index("id").reindex(df.columns, axis="columns")
# alternative (both lines lead to same output)
ordered_new_df = new_df.set_index("id")[df.columns]
print(ordered_new_df)
name type link subs
id
1 2 x tx 10 sub1 sub2
3 4 5 y rx 11 sub3 sub4 sub5请注意,您只需调用new_df.set_index("id")就可以得到“正确”的排序,但是我展示的方法更显着。
发布于 2021-06-25 20:55:48
使用由熊猫支持的datar很容易做到这一点,但是实现了dplyr类语法:
>>> from datar.all import (
... f, tribble,
... group_by, summarise, paste
... )
>>>
>>> df = tribble(
... f.id, f.name, f.type, f.link, f.subs,
... 1, "x", "tx", 10, "sub1",
... 2, "x", "tx", 10, "sub2",
... 3, "y", "rx", 11, "sub3",
... 4, "y", "rx", 11, "sub4",
... 5, "y", "rx", 11, "sub5",
... )
>>> df
id name type link subs
<int64> <object> <object> <int64> <object>
0 1 x tx 10 sub1
1 2 x tx 10 sub2
2 3 y rx 11 sub3
3 4 y rx 11 sub4
4 5 y rx 11 sub5
>>> df >> group_by(f.name, f.type, f.link) >> summarise(
... id = [f.id.values],
... subs = paste(f.subs, collapse=' ')
... )
[2021-06-25 13:55:18][datar][ INFO] `summarise()` has grouped output by ['name', 'type'] (overri
de with `_groups` argument)
name type link id subs
<object> <object> <int64> <object> <object>
0 x tx 10 [1, 2] sub1 sub2
1 y rx 11 [3, 4, 5] sub3 sub4 sub5
[Groups: name, type (n=2)]免责声明:我是datar软件包的作者。
https://stackoverflow.com/questions/68136875
复制相似问题