Note
Pandas (56) 본문
728x90
How to swap two rows of a dataframe?
# Input
df = pd.DataFrame(np.arange(25).reshape(5, -1))
# Solution
def swap_rows(df, i1, i2):
a, b = df.iloc[i1, :].copy(), df.iloc[i2, :].copy()
df.iloc[i1, :], df.iloc[i2, :] = b, a
return df
print(swap_rows(df, 1, 2))
# output
0 1 2 3 4
0 0 1 2 3 4
1 10 11 12 13 14
2 5 6 7 8 9
3 15 16 17 18 19
4 20 21 22 23 24
'Pandas' 카테고리의 다른 글
Pandas (57) (0) | 2022.10.19 |
---|---|
Pandas (55) (0) | 2022.10.14 |
Pandas (54) (0) | 2022.10.13 |
Pandas (52) (1) | 2022.09.21 |
Pandas (53) (0) | 2022.09.20 |
Comments