我有一張如下表。
| ID | 是的 | val1 | val2 | val3 | ... |
|---|---|---|---|---|---|
| 1 | 100 | 3 | 1 | 2 | |
| 1 | 150 | 1 | 2 | 4 | |
| 1 | 250 | 4 | 2 | 6 | |
| 2 | 200 | 3 | 1 | 4 | |
| 2 | 250 | 2 | 2 | 2 | |
| 2 | 350 | 4 | 2 | 4 | |
| 3 | 200 | 3 | 3 | 4 | |
| 3 | 300 | 3 | 2 | 4 | |
| 3 | 400 | 6 | 3 | 3 |
我想按 ID 聚合并按順序連接所有值,然后只取每個 id 的最后一個 y 。例如,該表如下所示:
| ID | 是的 | val1 | val2 | val3 | ... | val1 | val2 | val3 | ... | val1 | val2 | val3 | ... |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 250 | 3 | 1 | 2 | ... | 1 | 2 | 4 | ... | 4 | 2 | 6 | ... |
| 2 | 350 | 3 | 1 | 4 | ... | 2 | 2 | 2 | ... | 4 | 2 | 4 | ... |
| 3 | 400 | 3 | 3 | 4 | ... | 3 | 2 | 4 | ... | 6 | 3 | 3 | ... |
注意 y, 250 來自 id=1 的最后一行(在真實表中,我可以使用另一個 id 來指定要保留的 y),350 來自 id=2 的最后一行,400 來自最后一行id=3。這些值按順序簡單地連接成一行。
I looked into pivot_table and know I can use new_ds = pd.pivot_table(dataset, index='id') to aggregate by the ID, but I want to be selective (not including y for all rows, and in reality there's other garbage data I do not want). It is important that the values have to be in order, so the values from the second row come after the first, third comes the second etc. There's more than 100 values.
I've looked into pivot and groupby but can't figure out exactly how to apply to this.
uj5u.com熱心網友回復:
這不是一個資料透視表,而是一個時髦的 groupby,或者可能是兩個單獨的 groupby。
(我不會嘗試使用.agg()其中任何一個,因為您想將其他列按順序連接在一起,但是對于強迫您為每列.agg()定義一個單獨的聚合函式真的很迂腐,這會很痛苦。)
取組中的最后一個 'y' 值很容易:
df.groupby('id').agg({'y': lambda s: s.iloc[-1]})
# where we don't use .tail() to avoid the current bug on a series which throws "ValueError: Must produce aggregated value"
現在連續垂直連接組中的行,對于所有其他列:
我們實際上甚至不需要
pd.concat([...], axis=1)像我想的那樣我們可以在里面應用這個解決方案
df.groupby('id').apply(lambda g: g.drop(columns=['id','y']).values.flatten())首先,明確指定您希望包含哪些列:
df[['id','val1', 'val2', 'val3']].groupby('id').apply(lambda g: g.values.flatten())
id
1 [3, 1, 2, 1, 2, 4, 4, 2, 6]
2 [3, 1, 4, 2, 2, 2, 4, 2, 4]
3 [3, 3, 4, 3, 2, 4, 6, 3, 3]
或者,如果您愿意,可以將 移到.drop('y')前面:
df.drop(columns='y').groupby('id').apply(lambda g: g.values.flatten()
正如@DocZero 指出的那樣,我們不能合法地連接輸出中的重復列名,您的示例是非法語法。您需要弄清楚如何將前綴/后綴/其他名稱修飾添加到列名。
小提示:不鼓勵使用 pandas.values訪問器,并且將來會棄用,我們應該開始使用to_numpy()or.array。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/456656.html
下一篇:如何從熊貓行中增加某些列?
