簡體   English   中英

使用matplotlib和pandas從csv文件繪制直方圖

[英]plotting histogram from csv file using matplotlib and pandas

我的 csv 文件非常復雜。它包含數字和字符串屬性。 這就是我的 csv 文件的樣子在此處輸入圖片說明 我想繪制進程與 cpuid 的直方圖

您可以使用read_csv使用 str 進行索引並通過hist繪圖:

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()

圖形

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM