我的df是:
0 1 2
0 0 0 0
1 0 0 1
2 0 1 0
3 0 1 1
4 1 0 0
5 1 0 1
6 1 1 0
7 1 1 1
我想獲得一個列反轉/鏡像的資料框:
0 1 2
0 0 0 0
1 1 0 0
2 0 1 0
3 1 1 0
4 0 0 1
5 1 0 1
6 0 1 1
7 1 1 1
有沒有辦法做到這一點
uj5u.com熱心網友回復:
還有其他方法,但這里有一個解決方案:
df[df.columns] = df[reversed(df.columns)]
輸出:
0 1 2
0 0 0 0
1 1 0 0
2 0 1 0
3 1 1 0
4 0 0 1
5 1 0 1
6 0 1 1
7 1 1 1
uj5u.com熱心網友回復:
你可以檢查
df[:] = df.iloc[:,::-1]
df
Out[959]:
0 1 2
0 0 0 0
1 1 0 0
2 0 1 0
3 1 1 0
4 0 0 1
5 1 0 1
6 0 1 1
7 1 1 1
uj5u.com熱心網友回復:
這是一個更冗長但可能更有效的解決方案,因為它不需要重寫資料。它只重命名和重新排序列:
cols = df.columns
df.columns = df.columns[::-1]
df = df.loc[:,cols]
或更短的變體:
df = df.iloc[:,::-1].set_axis(df.columns, axis=1)
輸出:
0 1 2
0 0 0 0
1 1 0 0
2 0 1 0
3 1 1 0
4 0 0 1
5 1 0 1
6 0 1 1
7 1 1 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447965.html
標籤:python-3.x 熊猫 数据框 系列
