Using pandas, there is an short iterative solution to the problem.
First, let us construct a test dataframe called df
:
import pandas as pd
df = pd.DataFrame(
[
['Player1', 'PG'],
['Player2', 'SG'],
['Player3', 'SF'],
['Player4', 'PF'],
['Player5', 'C'],
['Player6', 'PG'],
['Player7', 'SF'],
['Player8', 'PF'],
['Player9', 'C'],
],
columns=['name', 'position']
)
df
Out[1]:
name position
0 Player1 PG
1 Player2 SG
2 Player3 SF
3 Player4 PF
4 Player5 C
5 Player6 PG
6 Player7 SF
7 Player8 PF
8 Player9 C
Then, we use the transform
method to create new columns (looping over the positions).
For each column, we use a lambda function returning 1 if the position is the one matching the column, and 0 otherwise:
for pos in ['PG', 'SG', 'SF', 'PF', 'C']:
df[pos] = df['position'].transform(lambda p: 1 if p == pos else 0)
df
Out[2]:
name position PG SG SF PF C
0 Player1 PG 1 0 0 0 0
1 Player2 SG 0 1 0 0 0
2 Player3 SF 0 0 1 0 0
3 Player4 PF 0 0 0 1 0
4 Player5 C 0 0 0 0 1
5 Player6 PG 1 0 0 0 0
6 Player7 SF 0 0 1 0 0
7 Player8 PF 0 0 0 1 0
8 Player9 C 0 0 0 0 1
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…