2017-10-07 68 views
1

我有以下的數據幀熊貓據幀情節線圖

| name | number | value | 
|------|--------|-------| 
| a | 1  | 13 | 
| a | 2  | 18 | 
| a | 3  | 54 | 
| b | 1  | 1  | 
| c | 1  | 135 | 
| c | 2  | 153 | 
| c | 3  | 512 | 
| d | 1  | 36 | 
| d | 2  | 74 | 
| d | 3  | 209 | 
| e | 1  | 108 | 
| e | 2  | 150 | 
| e | 3  | 339 | 
| f | 1  | 27 | 
| f | 2  | 41 | 
| f | 3  | 177 | 
| g | 1  | 102 | 
| g | 2  | 102 | 
| g | 3  | 360 | 
| h | 1  | 1  | 
| i | 1  | 1  | 

我希望做兩件事情...

  1. 在名稱列中的任何行只出現過一次,我希望將其從表格中移除,以便我的輸出結果是行'b','h'和'i'被刪除。

  2. 然後我想製作一個線圖,其中數字在x軸上,名稱在y軸上,線條穿過的是數值,我做了一個粗略的例子來展示什麼我的意思是(每行會是一個不同的顏色對應的名稱)

enter image description here

回答

2

你問了相當多的格式。但這裏是一個簡單的例子:

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

string = u"""number,name,value 
a,1,13 
a,2,15 
a,3,18 
b,1,1 
c,1,17 
c,2,21 
""" 

df = pd.read_csv(io.StringIO(string)) 

# Remove uniques with boolean indexing 
df = df[df.duplicated('number',keep=False)] 

#https://stackoverflow.com/questions/41494942/pandas-dataframe-groupby-plot 
df.set_index('name', inplace=True) 
df.groupby('number')['value'].plot(legend=True) 

plt.show() 

enter image description here

0

透視數據幀和情節

df[['number', 'value']] = df[['number', 'value']].astype(int) 
name_cnt = df.groupby('name').size() 
required_nm = name_cnt[ name_cnt != 1].index 
required_rows = df.loc[df.name.isin(required_nm)] # select non repeating row in 'name' columns 

required_rows.pivot(columns='name', index='number', values='value').plot()