基于熊猫数据框中的其他索引值分组索引值

问题描述 投票:0回答:1

我有一个具有以下结构的数据框


                     Sentence                 Label

A              B   
"unique ID1"   0    "Sample sentence 1"        jt
"unique ID1"   1   "Sample sentence 2"        jt  
"unique ID3"   2   "Sample sentence 3"        edu
"unique ID3"   3   "Sample sentence 4"        edu

我希望能够获得按索引B的值分组的索引A的所有值,其中label == jt并对所有唯一标签值重复。首选的返回类型是key-value对,但任何其他合适的格式也可以使用。

标签的有效示例== jt:

("unique ID1" : [0,1] )

标签的有效示例== edu:

("unique ID3" : [2,3] )

我已经尝试了许多SO问题,但还没有找到我想要的东西。

我也尝试过:



sorted_index_df = df.sort_index(inplace = False)

multi_index = sorted_index_df.loc[sorted_index_df["label"] == "jt"].index

这样做将返回索引A的每个值及其对应的索引B的值作为单独的元组。

例如:('Labor_&_Delivery_Nurse-APRN__Lidia_Lambert__', 17)

但是我希望能够通过索引B中的值对索引A的所有值进行分组。

感谢您的任何帮助。

python-3.x pandas hierarchical-data
1个回答
0
投票

您可以通过如下所示的groupby达到此目的>

df = pd.DataFrame([['unique ID1', '0', 'Sample sentence 1', 'jt'], ['unique ID1', '1', 'Sample sentence 2', 'jt'], ['unique ID3', '2', 'Sample sentence 3', 'edu'], ['unique ID3', '3', 'Sample sentence 4', 'edu']], columns=('A', 'B', 'Sentence', 'Label'))
result = df.groupby(["A", "Label"]).agg({"B":list}).reset_index(level=0)

## you can get result for jt like

result.loc["jt"]
© www.soinside.com 2019 - 2024. All rights reserved.