[英]How to merge rows in a pandas dataframe
我有一個看起來像這樣的 dataframe。 我通過合並兩個我已經擁有的具有所有相同標題的數據幀來獲得它。 問題是我在兩個數據框中都出現了一些行,它們需要合並。
指數 | ķ | e_K | 五 | e_V |
---|---|---|---|---|
1 | 2 | 5 | 6 | |
2 | 1 | 2 | 5 | |
3 | 2 | 3 | 2 | |
4 | 3 | 2 | 4 | |
5 | 5 |
所以需要合並第 1 行和第 2 行,以及第 3 行和第 4 行。(我也有很多缺失數據的行,比如我需要保留的第 5 行)。
預期 output:
指數 | ķ | e_K | 五 | e_V |
---|---|---|---|---|
1 | 1 | 2 | 5 | 6 |
3 | 2 | 3 | 2 | 4 |
5 | 5 |
我試過合並使用: df = df.groupby(['e_K', 'V']).first().reset_index() 刪除了我的一些行,其中沒有一個是重復的?
嘗試這個 -
a = [[None,1,2,None],
[3,1,2,None],
[3,1,2,5],
[None,5,2,1]]
df = pd.DataFrame(a)
cols_bool = df.notna().all(0)
uniques = df.iloc[df.loc[:,cols_bool].drop_duplicates().index]
print(uniques)
0 1 2 3
0 NaN 1 2 NaN
3 NaN 5 2 1.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.