在Python中合并两个数据集

时间:2017-12-06 12:49:59

标签: python csv numpy

我有两组x-y数据,其x值应该合并。为了说明,第一组看起来像这样:

0.5;3.4
0.8;3.8
0.9;1.2
1.3;1.1
1.9;2.3

第二组是这样的:

0.3;-0.2
0.8;-0.9
1.0;0.1
1.5;1.2
1.6;6.3

数据位于两个单独的csv文件中。我想将两个文件合并为一个,以便x值按顺序排列,y值显示在两列中,其中包含(线性)插值(y1和{ {1}})完成了。第二列包含第一个数据集的y2值(加上插值),第三列包含第二个数据集的y值。

y

到目前为止,我唯一的想法是将数据读入numpy数组,将它们连接在一起,对值进行排序并计算前后值的平均值,以防值为空。

在Python中有更优雅的方法吗?

编辑:这是我的尝试。它可以工作并提供我想象的结果,尽管脚本很长。

0.3;y1;-0.2
0.5;3.4;y2
0.8;3.8;-0.9
0.9;1.2;y2
1.0;y1;0.1
1.3;1.1;y2
1.5;y1;1.2
1.6;y1;6.3
1.9;2.3;y2

2 个答案:

答案 0 :(得分:1)

我会使用pandas进行此类处理:

import pandas as pd
#I assumed you have no headers in the data files
df1 = pd.read_csv('./dataset1.txt',sep=';',header=None)
df2 = pd.read_csv('./dataset2.txt',sep=';',header=None)
#Join the datasets using full outer join on the first column in both datasets
df_merged = df1.merge(df2, on=0, how='outer')
#Fill the nulls with the desirable values in this case the average of the column
df_merged['1_x'].fillna(df_merged['1_x'].mean(),inplace=True)
df_merged['1_y'].fillna(df_merged['1_y'].mean(),inplace=True)

输出:

print(df_merged)
    0   1_x 1_y
0   0.5 3.4 y2
1   0.8 3.8 -0.9
2   0.9 1.2 y2
3   1.3 1.1 y2
4   1.9 2.3 y2
5   0.3 y1  -0.2
6   1.0 y1  0.1
7   1.5 y1  1.2
8   1.6 y1  6.3

您可以轻松更改列名称:

df_merged.columns = ['col1','col2','col3']

您还可以使用sort_values方法轻松对值进行排序:

df_merged.sort_values('col1')

最后,您可以使用以下方法轻松地将此最终DataFrame转换为numpy数组:

import numpy as np
np.array(df_merged)

答案 1 :(得分:1)

一个班轮:dfi = pd.merge(df1,df2,'outer',0).set_index(0).sort_index().interpolate()

In [383]: dfi
Out[383]: 
      1_x   1_y
0              
0.3   NaN -0.20
0.5  3.40 -0.55
0.8  3.80 -0.90
0.9  1.20 -0.40
1.0  1.15  0.10
1.3  1.10  0.65
1.5  1.50  1.20
1.6  1.90  6.30
1.9  2.30  6.30

一个完整的熊猫版+ numpy插值,可以更好地调整边缘:

#df1 = pd.read_clipboard(header=None,sep=';')
#df2 = pd.read_clipboard(header=None,sep=';')

import pylab as pl

df = pd.merge(df1,df2,'outer',0).sort_values(0)
df['y1']=scipy.interpolate.interp1d(*df1.values.T,fill_value='extrapolate')(df[0])
df['y2']=scipy.interpolate.interp1d(*df2.values.T,fill_value='extrapolate')(df[0])

ax=pl.gca()
df1.set_index(0).plot(lw=0,marker='o',ax=ax)
df2.set_index(0).plot(lw=0,marker='o',ax=ax)
df.set_index(0).loc[:,['y1','y2']].plot(ax=ax)    
pl.show()

情节:

enter image description here

数据:

In [344]: df1
Out[344]: 
     0    1
0  0.5  3.4
1  0.8  3.8
2  0.9  1.2
3  1.3  1.1
4  1.9  2.3

In [345]: df2
Out[345]: 
     0    1
0  0.3 -0.2
1  0.8 -0.9
2  1.0  0.1
3  1.5  1.2
4  1.6  6.3

In [346]: df
Out[346]: 
     0  1_x  1_y         y1         y2
5  0.3  NaN -0.2 -20.713281  -0.200000
0  0.5  3.4  NaN   3.400000  -3.021563
1  0.8  3.8 -0.9   3.800000  -0.900000
2  0.9  1.2  NaN   1.200000  -0.092830
6  1.0  NaN  0.1  -0.265527   0.100000
3  1.3  1.1  NaN   1.100000  -1.960323
7  1.5  NaN  1.2   3.760937   1.200000
8  1.6  NaN  6.3   4.701230   6.300000
4  1.9  2.3  NaN   2.300000  44.318059