简体   繁体   English

如何重命名一个类似于名称的数字的数据框列?

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

I have a dataframe column contains 10 different digits.我有一个数据框列包含 10 个不同的数字。 Through pd.get_dummies I've got 10 new columns which column names are numbers.通过pd.get_dummies我有 10 个新列,列名是数字。 Then I want to rename these number named columns by df = df.rename(columns={'0':'topic0'}) but failed.然后我想通过df = df.rename(columns={'0':'topic0'})重命名这些编号命名的列,但失败了。 How can I rename these columns' name from numbers to strings?如何将这些列的名称从数字重命名为字符串?

Use DataFrame.add_prefix :使用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)})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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