2013-03-10 48 views
1

我有兩個DataFrames如何用Python /熊貓減去2列未對齊的數據?

df1= 

    x y1 
0 0 0 
1 1 1 
2 2 2 
3 4 3 


df2= 

    x y2 
0 0.0 0 
1 0.5 1 
2 1.5 2 
3 3.0 3 
4 4.0 4 

我需要計算Y2,Y1(同一x值) (以便看2幅圖之間的差)

正如你所看到的,一些值在他們之間是共同的...有些不是

我想我將需要重新採樣我的數據...但我不知道如何! 我需要對齊數據以便爲這兩個數據幀設置相同的'x'列。

2點之間應該進行線性插值以獲得給定x的y值。

在這種情況下有x_step重新採樣數據= 0.5將是很好的

我這樣做...

import pandas as pd 
import matplotlib.pylab as plt 

df1 = pd.DataFrame([[0.0,0.0],[1.0,1.0],[2.0,2.0],[4.0,3.0]],columns=['x','y1']) 
df2 = pd.DataFrame([[0.0,0.0],[0.5,1.9],[1.5,2.0],[3.0,3.0],[4.0,4.0]],columns=['x','y2']) 

print(df1) 
print("="*10) 
print(df1['x']) 
print("="*10) 
print(df1['y1']) 
print("="*10) 

fig = plt.figure() 

fig.subplots_adjust(bottom=0.1) 
ax = fig.add_subplot(111) 

plt.title("{y} = f({x})".format(x='x', y='y')) 
p1, = plt.plot(df1['x'], df1['y1'], color='b', marker='.') 
p2, = plt.plot(df2['x'], df2['y2'], color='r', marker='.') 

plt.legend([p1, p2], ["y1", "y2"]) 

plt.show() 

回答

1
import pandas as pd 
import pylab as pl 

df1 = pd.DataFrame([[0.0,0.0],[1.0,1.0],[2.0,2.0],[4.0,3.0]],columns=['x','y1']) 
df2 = pd.DataFrame([[0.0,0.0],[0.5,1.9],[1.5,2.0],[3.0,3.0],[4.0,4.0]],columns=['x','y2']) 
x = np.union1d(df1.x, df2.x) 
y1 = np.interp(x, df1.x, df1.y1) 
y2 = np.interp(x, df2.x, df2.y2) 
pl.plot(x, y1, "-o") 
pl.plot(x, y2, "-o") 

enter image description here

+0

情節都Y2和DF2 [ 'Y2' ] ...你會看到有一個問題(點x = 2)! http://pastebin.com/hipQCSZ4 http://imageshack.us/photo/my-images/203/capturedecran20130311a0.png/ – working4coins 2013-03-11 05:43:43

+0

似乎'Series.interpolate()'不使用索引值來插入NaN值。所以我改變了使用'numpy.interp()'的答案。 – HYRY 2013-03-11 07:24:47

+0

感謝它工作正常......我只是想知道爲什麼y1.interpolate()不適合NaN(以及如何插入nan數據!)......這很奇怪。 – working4coins 2013-03-11 17:35:05