【发布时间】:2018-03-11 01:46:27
【问题描述】:
我有这个数据框;请注意右侧的最后一列(“Yr_Mo_Date”)
In[38]: data.head()
Out[38]:
RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL Yr_Mo_Dy
0 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04 61-1-1
1 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83 61-1-2
2 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71 61-1-3
3 10.58 6.63 11.75 4.58 4.54 2.88 8.63 1.79 5.83 5.88 5.46 10.88 61-1-4
4 13.33 13.25 11.42 6.17 10.71 8.21 11.92 6.54 10.92 10.34 12.92 11.83 61-1-5
“Yr_Mo_Dy”列的类型是object,其他都是float64。
我只想更改列的顺序,使“Yr_Mo_Dy”成为数据框中的第一列。 我尝试了以下方法,但我得到了 TypeError。怎么了?
In[39]: cols = data.columns.tolist()
In[40]: cols
Out[40]:
['RPT',
'VAL',
'ROS',
'KIL',
'SHA',
'BIR',
'DUB',
'CLA',
'MUL',
'CLO',
'BEL',
'MAL',
'Yr_Mo_Dy']
In[41]: cols = cols[-1] + cols[:-1]
TypeError Traceback (most recent call last)
<ipython-input-59-c0130d1863e8> in <module>()
----> 1 cols = cols[-1] + cols[:-1]
TypeError: must be str, not list
【问题讨论】:
-
col[-1] 是字符串数据类型; col[1:] 是数据类型列表。您只能将列表添加到列表中,而不能将字符串添加到列表中。
-
cols = [cols[-1]] + cols[:-1]
标签: python list pandas typeerror