import pandas as pdimport matplotlib.pyplot as pltimport osplt.rcParams['font.sans-serif']=['SimHei']plt.rcParams['axes.unicode_minus']=Falsedef dataDescribeVisualization(): while True: fileName=input('请输入要打开的文件名presidential_polls_clinton_state_mean_lable.csv:') try: df_count=pd.read_csv(fileName,encoding='cp936') df_count=df_count.columns['Label'] df_count=df_count.value_counts() print(df_count) plt.figure() count_cut_counts.plot(kind='bar',figsize=(12,8)) plt.plot(df_count['Label'],df_count['个数'],label='个数',color='blue') plt.xlabel("Label",fontsize=12)#设置x轴标签 plt.ylabel("个数")#设置y轴标签 plt.xticks(OneSup, TwoSup, ThreeSup, FourSup)#设置x轴刻度 plt.title('列Lable的个数统计柱状图') plt.legend(figsize=16)#显示图例并设置字号 plt.savefig('presidential_polls_clinton_state_support.png',dpi=300) plt.show() print("任务6执行成功!") break except Exception as e: print(e)dataDescribeVisualization()import pandas as pdimport matplotlib.pyplot as pltimport osplt.rcParams['font.sans-serif']=['SimHei']plt.rcParams['axes.unicode_minus']=Falsedef dataDescribeVisualization(): while True: fileName=input('请输入要打开的文件名presidential_polls_clinton_state_mean_lable.csv:') try: df_count=pd.read_csv(fileName,encoding='cp936') df_count=df_count.columns['Label'] df_count=df_count.value_counts() print(df_count) plt.figure() count_cut_counts.plot(kind='bar',figsize=(12,8)) plt.plot(df_count['Label'],df_count['个数'],label='个数',color='blue') plt.xlabel("Label",fontsize=12)#设置x轴标签 plt.ylabel("个数")#设置y轴标签 plt.xticks(OneSup, TwoSup, ThreeSup, FourSup)#设置x轴刻度 plt.title('列Lable的个数统计柱状图') plt.legend(figsize=16)#显示图例并设置字号 plt.savefig('presidential_polls_clinton_state_support.png',dpi=300) plt.show() print("任务6执行成功!") break except Exception as e: print(e)dataDescribeVisualization()
报错:only integers, slices (:
), ellipsis (...
), numpy.newaxis (None
) and integer or boolean arrays are valid indices
行数只要当文本文件读然后计算,以下2种方法都可以:
with open("test.csv","r",encoding='UTF-8') as f:
lines1 = len(f.readlines())
print(lines1)
with open("test.csv","r",encoding='UTF-8') as f:
lines2 = f.read().count('\n')+1
print(lines2)
可以导入 csv
库。
示例:
import csv
with open("test.csv","r") as f:
reader=csv.reader(f) #读取 CSV 文件
for i in reader: #循环列出 CSV 表格的每一行
print(i)