读取特定行和特定列的csv文件,作图

文章介绍了使用Python的pandas库读取CSV文件,解析日期,然后利用matplotlib绘制不同时间下行总流量的图表的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

也是参考各位优快云大佬的代码,融合在一起,侵删。

import csv
import matplotlib.pyplot as plt

import pandas as pd
from datetime import datetime
file_name = 'E:\data\\0721-0727.csv'

with open(file_name, 'r', encoding='utf-8') as f:
    reader = csv.reader(f)

    for i in range(6):
        header_row = next(reader)

    dates, blocks, ltes = [], [], []
    for row in reader:
        try:
            current_date = datetime.strptime(row[1][0:row[1].rfind('-')], '%Y.%m.%d %H:%M')
            block=str(row[0])
            lte=str(row[29])

            if block=='###':
                print(current_date)
                print(block)
                print(lte)
            else:
                break #shi

        except ValueError:
            print(current_date, 'missing date')

        else:
            dates.append(current_date)
            blocks.append(block)
            ltes.append(lte)


    test=pd.DataFrame({'BLOCK':blocks,'DATAS':dates,'LTES':ltes})
    test.to_csv('test.csv',index = None,encoding='utf8')

    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['font.family'] = 'sans-serif'
    plt.rcParams['axes.unicode_minus'] = False

    data1 = pd.read_csv('test.csv')

    fig = plt.figure(figsize=(36, 24))
    xdata = []
    ydata = []

    xdata = data1.loc[:, 'DATAS']
    ydata = data1.loc[:, 'LTES']

    plt.plot(xdata, ydata, color='r', marker='o', mec='r', mfc='w', label=u'LTE_下行总流量[单位:MByte]')
    plt.xticks(rotation=45)

    plt.title(u"不同时间下行总流量图", size=40)
    plt.legend()
    plt.xlabel(u'时间', size=40)
    plt.ylabel(u'下行总流量,单位MByte', size=40)

    plt.show()
### 如何使用 Python Pandas 读取 CSV 文件并用 Matplotlib 绘制直方图 要实现通过 Python 的 `Pandas` 库读取 CSV 文件,并借助 `Matplotlib` 库绘制直方图,可以按照以下方法完成。 #### 方法一:基于单数据绘制直方图 以下是完整的代码示例: ```python import os import matplotlib.pyplot as plt import pandas as pd def draw_histogram(csv_file, column_index=1, bins=None): """ 使用 Pandas Matplotlib 绘制指定 CSV 的直方图。 参数: csv_file (str): CSV 文件路径。 column_index (int): 要绘制直方图的目标索引,默认为第二(即索引为1)。 bins (int or None): 历史柱状图的数量。如果未提供,则自动计算。 """ # 加载 CSV 数据到 DataFrame 中 reviews = pd.read_csv(csv_file) # 获取目标的数据 target_column_data = reviews.iloc[:, column_index] # 创建直方图 plt.hist(target_column_data, bins=bins) plt.title('Histogram of Column Data') plt.xlabel('Value') plt.ylabel('Frequency') # 显示图表并将图片保存至同一目录下 plt.show() output_image_path = os.path.join(os.path.dirname(csv_file), 'histogram.png') plt.savefig(output_image_path) def main(): csv_file = r'/path/to/your/file.csv' draw_histogram(csv_file, column_index=1, bins=20) if __name__ == '__main__': main() ``` 上述代码实现了从 CSV 文件中提取特定的数据,并将其绘制成直方图[^1]。其中,函数参数允许灵活调整所选以及直方图中的区间数量。 --- #### 方法二:动态设置直方图区间的数量 当不确定最佳区间数时,可以通过统计学方法自动生成合理的区间数目。例如,Sturges 公式可用于估算合适的区间数 $k$: $$ k = \lceil\log_2(n)\rceil + 1 $$ 这里 $n$ 是样本大小。此逻辑可嵌入代码中以增强自动化程度[^4]。 ```python import math def calculate_bins(data_length): """ 计算推荐的直方图区间数 """ return int(math.ceil(math.log2(data_length)) + 1) bins_number = calculate_bins(len(reviews)) plt.hist(reviews[header[column_index]], bins=bins_number) ``` 这种方法能够更科学地决定直方图分区,从而提升可视化效果的质量。 --- #### 注意事项 - 如果 CSV 文件较大或者存在缺失值,在加载前应考虑预处理步骤来优化性能准确性。 - 对于非数值型字段尝试作图可能会引发错误;因此建议先验证待分析的内容类型是否适合用于构建直方图[^3]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值