1

I've got a numpy array and I want to rename its columns with the schematic:

sid | sx1...-sx2048 | I decided to use dict:

train_set.rename(columns = {0:'sid'}, inplace = True) 
train_set.rename(columns=dict(zip(train_set.columns[1:2048],(np.full(2048,'sx' + str(indexes[0:2047]))))),inplace = True) 

but of course it's wrong because now I've got columns with names sx[1....2048] sx[1...2048 and so on.

I've changed this line in different ways but either it didn't work or there was an error:

ufunc 'add' did not contain a loop with signature matching types (dtype('<U11175'), dtype('<U11175')) -> dtype('<U11175')

Can anyone has an idea how to do this using dict?

Thank you for your response!

Greetings Alex

Leks
  • 31
  • 4

1 Answers1

0

You can merge 2 dictionaries with ** and pass to rename:

df = pd.DataFrame({
        0:list('abcdef'),
        1:[4,5,4,5,5,4],
        2:[7,8,9,4,2,3],
        3:[1,3,5,7,1,0],
        4:[5,3,6,9,2,4],
        5:list('aaabbb')
})


d = {**{0:'sid'}, **dict(zip(df.columns[1:], 'sx' + df.columns[1:].astype(str)))}
df = df.rename(columns=d)
print (df)
  sid  sx1  sx2  sx3  sx4 sx5
0   a    4    7    1    5   a
1   b    5    8    3    3   a
2   c    4    9    5    6   a
3   d    5    4    7    9   b
4   e    5    2    1    2   b
5   f    4    3    0    4   b

If want set values by positions:

df.columns = ['sid'] + [f'sx{i}' for i in range(1, len(df.columns))]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252