Reputation: 327
I have a dataframe column contains 10 different digits. Through pd.get_dummies
I've got 10 new columns which column names are numbers. Then I want to rename these number named columns by df = df.rename(columns={'0':'topic0'})
but failed. How can I rename these columns' name from numbers to strings?
Upvotes: 2
Views: 567
Reputation: 863301
Use DataFrame.add_prefix
:
df = pd.DataFrame({'col':[1,5,7,8,3,6,5,8,9,10]})
df1 = pd.get_dummies(df['col']).add_prefix('topic')
print (df1)
topic1 topic3 topic5 topic6 topic7 topic8 topic9 topic10
0 1 0 0 0 0 0 0 0
1 0 0 1 0 0 0 0 0
2 0 0 0 0 1 0 0 0
3 0 0 0 0 0 1 0 0
4 0 1 0 0 0 0 0 0
5 0 0 0 1 0 0 0 0
6 0 0 1 0 0 0 0 0
7 0 0 0 0 0 1 0 0
8 0 0 0 0 0 0 1 0
9 0 0 0 0 0 0 0 1
Upvotes: 2
Reputation: 7922
With the example dataframe you can do:
d = {0: [1, 2], 1: [3, 4]}
df = pd.DataFrame(data=d)
You can do for example:
df.rename(index=str, columns={0: "a", 1: "c"})
And then use this method to rename the other columns.
Compactly:
for x in range(3):
df.rename(index=str, columns={x: "topic"+str(x)})
Upvotes: 0