本文主要是介绍对DataFrame数据按列处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
对DataFrame数据按列处理
获取列名使用.columns()函数。
import pandas as pd
df=pd.DataFrame({'id':[1,2,3,4,5],'a':[1, 3, 5, 7,9],'b':[2 , 4 , 6, 8, 19], 'c': [4, 6, 9, 12, 20],'d':['yes','yes','no','no','yes']})
df
id | a | b | c | d | |
---|---|---|---|---|---|
0 | 1 | 1 | 2 | 4 | yes |
1 | 2 | 3 | 4 | 6 | yes |
2 | 3 | 5 | 6 | 9 | no |
3 | 4 | 7 | 8 | 12 | no |
4 | 5 | 9 | 19 | 20 | yes |
df.columns
Index(['id', 'a', 'b', 'c', 'd'], dtype='object')
注意df.columns的类型是Index,不可修改。
type(df.columns)
pandas.core.indexes.base.Index
df.columns[1]='d'
---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-12-ed755c965e42> in <module>
----> 1 df.columns[1]='d'C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in __setitem__(self, key, value)3908 3909 def __setitem__(self, key, value):
-> 3910 raise TypeError("Index does not support mutable operations")3911 3912 def __getitem__(self, key):TypeError: Index does not support mutable operations
如果要提取df中的某些列,比如需要对于数值类型和文本类型的列做不同的处理,就需要将二者分开。这里的文本类型是’d’,另外,'id’也不必参与到后续的数据处理当中去。
cate=['d']
num=df.columns.drop(cate).drop('id')
num
Index(['a', 'b', 'c'], dtype='object')
注意此处的.drop()会在不影响df.columns的内容的情况下生成一个去除了其中含有的cate之后的副本,如果其中不含有drop的内容还会报错,在对不同类型的列做处理时很实用。
与此对应,.remove()会在原列表上删除对象(所以对于Index是不可用的,对list可用),不产生副本,各有适用场合。
如果想获得列名称并进行操作,使用.tolist()。
col_name=df.columns.tolist()
type(col_name)
list
data_cate=df[cate]
data_num=df[num]
将数值型和文本型数据分开后可用分别处理,例如数值型做标准化,文本型做编码。如果需要把经过分别处理后的数据合成一个表,可以使用pd.concat()函数。
data_processed=pd.concat([data_cate,data_num],axis=1)
data_processed
d | a | b | c | |
---|---|---|---|---|
0 | yes | 1 | 2 | 4 |
1 | yes | 3 | 4 | 6 |
2 | no | 5 | 6 | 9 |
3 | no | 7 | 8 | 12 |
4 | yes | 9 | 19 | 20 |
这篇关于对DataFrame数据按列处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!