python的DataFrame排序问题

(七) 

python的DataFrame排序问题


1.按照一列排序

  1. frame.sort_index(axis = 0,ascending = True,by = 'a')  #升序

   frame.sort_index(axis = 0,ascending = False,by = 'a') #降序

2.  按多列排序

frame.sort_index(axis = 0,ascending = True,by = ['b','c','a'])

3.  按行排序

frame.sort_index(axis = 1,ascending = True)

按照列排序后,index没有重新编写。需要将index重新设置

如下

  1. frame.sort_index(axis = 0,ascending = False,by = ['b','c','a'])  
  2.   
  3. Out[78]:   
  4.    a  b  c  
  5. 1  2  7  5  
  6. 0  9  4  6  
  7. 5  7  2  4  
  8. 4  0  2  4  
  9. 3  1  2  3  
  10. 2  5 -3  8  

用 frame= frame.reset_index(drop=True) 来将index重新设置

扫描二维码关注公众号,回复: 2479495 查看本文章

也可以使用sort_values排序,老版本中为sort_index。

[python]  view plain  copy
  1. import pandas as pd  
  2. df = pd.DataFrame([[1,2,3],[2,3,4],[2,4,3],[1,3,7]],  
  3.                   index = ['one','two','three','four'],columns = ['A','B','C'])  
  4. print df  
  5. #        A  B  C  
  6. # one    1  2  3  
  7. # two    2  3  4  
  8. # three  2  4  3  
  9. # four   1  3  7  
  10. df.sort_values(by=['A','B'],ascending=[0,1],inplace=True
    1.  #A为降序,b为升序,inplace=True代表结果按照排#序来,否则输出的df还是原来的样子

  11. print df  
  12. #        A  B  C  
  13. # two    2  3  4  
  14. # three  2  4  3  
  15. # one    1  2  3  
  16. # four   1  3  7  

4. 在pandas的DataFrame中,我们经常需要根据某属性来选取指定条件的行,这时isin方法就特别有效

[python]  view plain  copy
  1. import pandas as pd  
  2. df = pd.DataFrame([[1,2,3],[1,3,4],[2,4,3]],index = ['one','two','three'],columns = ['A','B','C'])  
  3. print df  
  4. #        A  B  C  
  5. # one    1  2  3  
  6. # two    1  3  4  
  7. # three  2  4  3  
这时假设我们选取A列中值为1的行,
[python]  view plain  copy
  1. mask = df['A'].isin([1]) #括号中必须为list  
  2. print mask  
  3. # one       True  
  4. # two       True  
  5. # three    False  
  6. # Name: A, dtype: bool  
  7. print df[mask]  
  8. #      A  B  C  
  9. # one  1  2  3  
  10. # two  1  3  4  

(八) dataframe.shape 返回一个元组包含df的维度信息即行数和列数,(row,col)

在pandas中遍历DataFrame行

Pandas基础-DataFrame-增删改查

(九)字典存为csv,键值为表头

with open(datafilepath + "params.csv",'w') as f:
    writer = csv.DictWriter(f,params.keys())
    writer.writeheader()

    writer.writerow(params)

(十)字典值排序和字典键名修改

排序: sorted(dict1,key = )

键名修改(键入键名为字符串)

dict2 = dict1.copy()   两字典不指向同一地址,修改dict1不会改变dict2(书上讲的是修改dict1会改变dict2,但我在使用过程中发现修改dict1不会改变dict2,修改dict2也不会改变dict1)

for key in dict2.keys():

     dict1[key[:-4]] = dict1.pop(key) 修改键名删除原键名合为一句


猜你喜欢

转载自blog.csdn.net/u013344884/article/details/79723139
今日推荐