你可以使用下面的基本语法来删除pandas中的重复列:
df.T.drop_duplicates().T
下面的例子展示了如何在实践中使用这种语法。
例子:在Pandas中删除重复的列
假设我们有如下的pandas DataFrame:
import pandas as pd
#create DataFrame with duplicate columns
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'points': [25, 12, 15, 14, 19, 23, 25, 29],
'assists': [25, 12, 15, 14, 19, 23, 25, 29],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
df.columns = ['team', 'points', 'points', 'rebounds']
#view DataFrame
df
team points points rebounds
0 A 25 25 11
1 A 12 12 8
2 A 15 15 10
3 A 14 14 6
4 B 19 19 6
5 B 23 23 5
6 B 25 25 9
7 B 29 29 12
我们可以使用下面的代码来删除重复的'point'列:
#remove duplicate columns
df.T.drop_duplicates().T
team points rebounds
0 A 25 11
1 A 12 8
2 A 15 10
3 A 14 6
4 B 19 6
5 B 23 5
6 B 25 9
7 B 29 12
注意,'points'列已经被删除,而所有其他的列仍然留在DataFrame中。
还值得注意的是,即使列的名称不同,但包含相同的值,这段代码也会删除重复的列。
例如,假设我们有下面这个pandas DataFrame:
import pandas as pd
#create DataFrame with duplicate columns
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'points': [25, 12, 15, 14, 19, 23, 25, 29],
'points2': [25, 12, 15, 14, 19, 23, 25, 29],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
#view DataFrame
df
team points points2 rebounds
0 A 25 25 11
1 A 12 12 8
2 A 15 15 10
3 A 14 14 6
4 B 19 19 6
5 B 23 23 5
6 B 25 25 9
7 B 29 29 12
注意,"points "和 "points2 "列包含相同的值。
我们可以使用下面的代码来删除重复的'point2'列:
#remove duplicate columns
df.T.drop_duplicates().T
team points rebounds
0 A 25 11
1 A 12 8
2 A 15 10
3 A 14 6
4 B 19 6
5 B 23 5
6 B 25 9
7 B 29 12
其他资源
下面的教程解释了如何在pandas中执行其他常见的功能: