簡體   English   中英

pandas 中的組合/合並值

[英]Combining/merging values in pandas

我在一列中有單個 class 的多個值,我想組合/合並它們。 我嘗試了以下代碼,但它只是根據每個等級合並值。

df.groupby('Grades')['Students'].apply(' '.join).reset_index()

我不想要這個。 假設我們有以下 DataFrame:

+----------------------------------+--------+
|             Students             | Grades |
+----------------------------------+--------+
| Student1                         |      0 |
| Student1                         |      1 |
| Student1                         |      2 |
| Student2                         |      3 |
| Student2                         |      5 |
| Student2                         |      0 |
| Student3                         |      1 |
| Student3                         |      0 |
| Student3                         |      0 |
+----------------------------------+--------+

我想要以下 DataFrame:

+----------------------------------+--------+
|             Students             | Grades |
+----------------------------------+--------+
| Student1                         |      1 |
| Student2                         |      3 |
| Student3                         |      0 |
+----------------------------------+--------+

我想合並學生並隨機取他/她的一個成績。 即使除了成績之外還有更多列,我希望在合並它們時為每個學生隨機選擇它們。

乍一看,我找到了兩種方法來完成相同的任務,但可能還有很多其他方法。

第一個洗牌整個 DataFrame 和每個組(學生的成績)取第一(隨機)行:

df.sample(frac=1.0).groupby("Students").first().reset_index()

相反,第二種方法為每個學生隨機取一行(從而避免整個數據集的洗牌):

df.groupby("Students").apply(lambda x: x.sample(n=1)).reset_index(drop=True)

你應該看看:

df.sample(frac=1.0)\
    .groupby(['Students']) \
    .agg(any_grades = ('rnd_grade','first'),
         any_other_col = ('other_col','first')) \
    .reset_index()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM