I have a pandas data frame with 1000 columns. Lets say I would like to rename columns 100 to 499 to ['x1','x2',....,'x400']. Is there any way to do it in pandas data frame without individually renaming each column? I am aware how to do multiple renaming I just want to figure out if it's possible to do it for a series of columns without the need to specify each column's name (I don't want to write 1000 column names individually in dataframe.columns
).
Create dictionary first and then rename
:
np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(3,10)), columns=list('abcdefghij'))
print (df)
a b c d e f g h i j
0 8 8 3 7 7 0 4 2 5 2
1 2 2 1 0 8 4 0 9 6 2
2 4 1 5 3 4 4 3 7 1 1
a = df.columns[np.arange(4,8)]
b = ['x' + str(i) for i in np.arange(1,len(a)+1)]
d = dict(zip(a, b))
print (d)
{'h': 'x4', 'e': 'x1', 'f': 'x2', 'g': 'x3'}
df = df.rename(columns=d)
print (df)
a b c d x1 x2 x3 x4 i j
0 8 8 3 7 7 0 4 2 5 2
1 2 2 1 0 8 4 0 9 6 2
2 4 1 5 3 4 4 3 7 1 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With