python (pandas) - 连接列表时出现 TypeError : must be str, 未列出

标签 python list pandas typeerror

我有这个数据框;请注意右侧的最后一列(“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”成为数据框中的第一列。 我尝试了以下方法,但出现类型错误。怎么了?

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

最佳答案

您需要为一个元素列表添加 :,因为需要连接 2 个列表:

#string
print (cols[-1])
Yr_Mo_Dy

#one element list
print (cols[-1:])
['Yr_Mo_Dy']

cols = cols[-1:] + cols[:-1]

或者可以添加[],但可读性较差:

cols = [cols[-1]] + cols[:-1]

print (cols)
['Yr_Mo_Dy', 'RPT', 'VAL', 'ROS', 'KIL', 'SHA', 'BIR', 
 'DUB', 'CLA', 'MUL', 'CLO', 'BEL', 'MAL']

关于python (pandas) - 连接列表时出现 TypeError : must be str, 未列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46483996/

相关文章:

r - 如何为列表中的项目指定连续名称?

python - 将数据框中的列与单个列表中的许多项目进行比较,并挑选出公共(public)元素

python - drop_duplicates - ValueError : keep must be either "first", "last"或 False

python - 刚性转换 - Python - 加速

python - PyQ5t : load Qt Designer into Python script (loadUiType): how to check error cause?

C# 从整数列表中删除项目 int[] l = {1,2,3} - 或使用递归添加它们

Python - 如何合并和交换两个列表的每个第 n 个元素

python - Pandas :具有复杂条件的数据框自连接

python - 如何在ubuntu中设置crontab的路径

Python Flask 400 Bad Request 每个请求都会出错