用pandas进行数据分析,对数据预处理,以及简单例子说明
- concat
用于将2个DataFrame连接到一起,一般是将训练集与测试集连接在一起对属性值进行预处理。个人感觉这样处理是可以的,因为对属性值的处理一般要求数值越多越好,而且对训练集与测试集的数据预处理要求要是一样的。只要在训练模型的时候讲2者分开就行。
相同列合并到一起,不同时新建列,缺省值为NaN
df1 =DataFrame({'a':[1,2,3],'b':[4,5,6]})
df2 =DataFrame({'a':['a','b','c'],'c':['e','f','g']})
df = pd.concat([df1,df2])
print df
"""
a b c
0 1 4 NaN
1 2 5 NaN
2 3 6 NaN
0 a NaN e
1 b NaN f
2 c NaN g
"""
df.reset_index(inplace=True)
print df
"""
index a b c
0 0 1 4 NaN
1 1 2 5 NaN
2 2 3 6 NaN
3 0 a NaN e
4 1 b NaN f
5 2 c NaN g
"""
df.drop('index', axis=1,inplace=True)
print df
"""
a b c
0 1 4 NaN
1 2 5 NaN
2 3 6 NaN
3 a NaN e
4 b NaN f
5 c NaN g
"""
df =df.reindex_axis(df1.columns, axis=1)
print df
"""
a b
0 1 4
1 2 5
2 3 6
3 a NaN
4 b NaN
5 c NaN
"""
df.shape[0],df.shape[1]分别获取行数、列数
print df.shape[1],"columns:", df.columns.values
print "Row count:",df.shape[0]
"""
2 columns: ['a' 'b']
Row count: 6
"""
- map()
Series 或 DataFrame 的列都可以调用一个map()方法。该方法接受一个函数或字典作为参数,并将之应用于该列的每一个元素,将元素值映射为另一个值。多用于数据离散化。
df = DataFrame(np.arange(8).reshape(4,2),columns= ['a','b'])
df['c'] = df['a'].map(lambda x: x+1)
print df
"""
a b c
0 0 1 1
1 2 3 3
2 4 5 5
3 6 7 7
"""
也可以在原来列修改值。df['a'] =df['a']. map({xxx})
"""