【问题标题】:plotting histogram from csv file using matplotlib and pandas使用 matplotlib 和 pandas 从 csv 文件中绘制直方图
【发布时间】:2016-07-03 16:29:35
【问题描述】:

我的 csv 文件非常复杂。它包含数字和字符串属性。 这就是我的 csv 文件的样子 我想绘制进程与 cpuid 的直方图

【问题讨论】:

  • 您能否展示您尝试过的内容,例如您没有发布任何加载数据的代码或尝试过任何有据可查的plotting methods
  • 使用 read_csv() function 将 csv 作为 pandas DataFrame 读取。
  • 如果第二列中只有cpu_id,那么简单地为列提供标题“cpu_id”并从字段中删除(搜索/替换)除值 0 之外的所有内容是否有意义/1?

标签: python csv pandas matplotlib histogram


【解决方案1】:

您可以使用read_csvindexing with strhist 绘图:

import pandas as pd
import matplotlib.pyplot as plt
import io

temp=u"""kmem_kmalloc;{cpu_id=1}
kmem_kmalloc;{cpu_id=1}
kmem_kmalloc;{cpu_id=1}
kmem_kmalloc;{cpu_id=1}
kmem_kfree;{cpu_id=1}
kmem_kfree;{cpu_id=1}
power_cpu_idle;{cpu_id=0}
power_cpu_idle;{cpu_id=0}
power_cpu_idle;{cpu_id=3}"""

s = pd.read_csv(io.StringIO(temp), #after testing replace io.StringIO(temp) to filename
                sep=";", #set separator, if sep=',' can be omited (default sep = ,)
                header=None, #no header in csv
                names=[None,'cpuid'], #set names of columns, (first is None because index)
                index_col=0, #first column set to index
                squeeze=True) #try convert DataFrame to Series
print s
kmem_kmalloc      {cpu_id=1}
kmem_kmalloc      {cpu_id=1}
kmem_kmalloc      {cpu_id=1}
kmem_kmalloc      {cpu_id=1}
kmem_kfree        {cpu_id=1}
kmem_kfree        {cpu_id=1}
power_cpu_idle    {cpu_id=0}
power_cpu_idle    {cpu_id=0}
power_cpu_idle    {cpu_id=3}
Name: cpuid, dtype: object
#if max cpu <= 9, use Indexing with .str 
s = s.str[-2].astype(int)

#if cpu > 9 
#s= s.str.extract('(\d)', expand=False)
print s
kmem_kmalloc      1
kmem_kmalloc      1
kmem_kmalloc      1
kmem_kmalloc      1
kmem_kfree        1
kmem_kfree        1
power_cpu_idle    0
power_cpu_idle    0
power_cpu_idle    3
Name: cpuid, dtype: int32

plt.figure();
s.hist(alpha=0.5)
plt.show()

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2015-10-25
    • 2014-02-28
    相关资源
    最近更新 更多