python - 将字符串中的列名称分配给数据框 - Python

标签 python pandas

我在Python中有以下字符串(不是列表,是字符串):

a = ['cc_call_center_sk', 'cc_call_center_id', 'cc_rec_start_date', 'cc_rec_end_date']

我还有以下数据框:

   0      1      2      3
0  AA     AB     BC     CD
1  AZ     ZR     RT     TN

我想要做的是将字符串“a”分配给数据帧的列。我这样做了:

df.columns = a

但我收到以下错误:

TypeError: Index(...) must be called with a collection of some kind, 
"['cc_call_center_sk', 'cc_call_center_id', 'cc_rec_start_date', 
'cc_rec_end_date']" was passed

我无法将字符串直接传递到 df.columns。对此有什么想法吗?谢谢!!!!

最佳答案

您需要通过 ast.literal_eval 将字符串转换为列表:

import ast

df.columns = ast.literal_eval(a)

另一个使用 stripsplit 的解决方案,最后删除每个列名称的 ':

a = "['cc_call_center_sk', 'cc_call_center_id', 'cc_rec_start_date', 'cc_rec_end_date']"

#solution 1
df.columns = [x.strip("'") for x in a.strip("[]").split(', ')]
#solution 2
df.columns = pd.Index(a.strip('[]').split(', ')).str.strip("'")

print (df)
  cc_call_center_sk cc_call_center_id cc_rec_start_date cc_rec_end_date
0                AA                AB                BC              CD
1                AZ                ZR                RT              TN

关于python - 将字符串中的列名称分配给数据框 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52810340/

相关文章:

python - 使用 Pandas 自定义排名选择

python - 在 Pandas 中如何根据列的值对多索引的一个级别进行排序,同时保持另一级别的分组

python - 如何使用python从github正确下载json文件

python - 无法使用 '...\python.exe' 创建进程 |虚拟环境错误

python - 在 Django 中,如何序列化 mptt 树?

python - 绘制差异较大的两个数据

python - AWS Elasticbeanstalk : Command 02_createadmin failed 上的 Django

python - exception_on_overflow参数不起作用? PyAudio的

python - 在 pandas 系列上使用 apply 方法获取 TypeError 'Series' 对象是可变的,因此无法对其进行哈希处理

python - Pandas 4 列表比较