I am trying to rename the '0' to 'predicted' as per below I receive no error but when I print it, it still shows as '0'?
df2 = pd.DataFrame(data)
df2.rename(columns = {'0':'predicted'}, inplace=True)
print (df2.tail())
0
248 0.335400
249 0.334992
250 0.334955
251 0.335716
252 0.335723
I believe 0
is integer
, so change '0'
(string) to 0
(number):
df2.rename(columns = {0:'predicted'}, inplace=True)
But better is use parameter columns in DataFrame
constructor:
df2 = pd.DataFrame(data, columns=['predicted'])
Here is another generic solution which should work for both - columns as numbers and columns as string representation of numbers:
Sample DF:
In [32]: df = pd.DataFrame(np.arange(15).reshape(-1,5), columns=[0,'1',2,'colX','colZ'])
In [33]: df
Out[33]:
0 1 2 colX colZ
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
In [34]: df.columns.tolist()
Out[34]: [0, '1', 2, 'colX', 'colZ']
Mapping:
In [29]: d = {'0':'col0','1':'col1','2':'col2'}
Renaming:
In [35]: df = df.rename(columns=lambda col: d.get(str(col)) if str(col) in d else col)
In [36]: df
Out[36]:
col0 col1 col2 colX colZ
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
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