如何重命名类似于数字的数据帧列?

2024-04-19 12:26:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧列包含10个不同的数字。通过pd.get_dummies我得到了10个新列,这些列的名称是数字。然后我想用df = df.rename(columns={'0':'topic0'})重命名这些编号为的列,但失败了。如何将这些列的名称从数字重命名为字符串?你知道吗


Tags: columns数据字符串名称dfget数字编号
2条回答

使用示例数据帧,您可以执行以下操作:

d = {0: [1, 2], 1: [3, 4]}
df = pd.DataFrame(data=d)

例如,您可以执行以下操作:

df.rename(index=str, columns={0: "a", 1: "c"})

然后使用此方法重命名其他列。你知道吗

紧凑地:

for x in range(3):
    df.rename(index=str, columns={x: "topic"+str(x)})

使用^{}

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

相关问题 更多 >