2016-09-26 133 views

回答

1

可以使用where上方和下方0新列bc選擇值:

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 

np.random.seed(1) 
data = np.random.randn(10) 
df = pd.DataFrame({'a':data}) 

df['b'] = df.a.where(df.a >= 0) 
df['c'] = df.a.where(df.a < 0) 
print (df) 
      a   b   c 
0 1.624345 1.624345  NaN 
1 -0.611756  NaN -0.611756 
2 -0.528172  NaN -0.528172 
3 -1.072969  NaN -1.072969 
4 0.865408 0.865408  NaN 
5 -2.301539  NaN -2.301539 
6 1.744812 1.744812  NaN 
7 -0.761207  NaN -0.761207 
8 0.319039 0.319039  NaN 
9 -0.249370  NaN -0.249370 

#plot to same figure 
ax = df.b.plot.bar(color='b') 
df.c.plot.bar(ax=ax, color='r') 
plt.show() 

graph

0

使用numpy.where可以獲得數據低於0的索引:np.where(x < 0)並超過0:np.where(x >= 0),因此您將得到兩個不重疊的數組,您可以使用不同的顏色進行可視化。 其實,熊貓框架有其自身的numpy.where當量,請看看這個問題:pandas equivalent of np.where

相關問題