简体   繁体   中英

how to rename a dataframe column which is a digit like name?

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?

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

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)})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM