python数据帧的列(从csv文件导入)与python关键字冲突,如何克服这种情况

时间:2018-04-29 15:16:13

标签: python machine-learning

Hello Machine学习和Python专家,

我正在尝试为数据框的一列绘制条形图,但我收到如下错误,

x_all.class.value_counts().plot(kind='bar')
      ^
SyntaxError: invalid syntax 

错误是因为列名" class"与python关键字相同.i被告知不要更改列的名称" class"。 如何在不更改列名的情况下绘制图形?

完整代码如下:

import numpy as np       
import pandas as pd    
import matplotlib.pyplot as plt   `enter code here`
train = pd.read_csv("network_train.csv")    
test = pd.read_csv("network_test.csv")    
x_all=pd.concat((train,test),axis=0)
x_all.class.value_counts().plot(kind='bar')

列"类"的屏幕截图给出了enter image description here

1 个答案:

答案 0 :(得分:0)

尝试:

getattr(x_all,'class').value_counts().plot(kind='bar')

如果它不起作用,您需要在CSV文件中重命名列名:

with open("network_train.csv") as infile, open('new_network_train.csv','w') as outfile: 
for line in infile: 
    outfile.write(line.replace('class','class1'))

with open("network_test.csv") as infile, open('new_network_test.csv','w') as outfile: 
for line in infile: 
    outfile.write(line.replace('class','class1'))

并使用新文件。