当前位置:   article > 正文

14.Python 通过列标题取列所有值_python查看某一列有哪些取值

python查看某一列有哪些取值

1.基础python 语法

  1. vi 7csv_reader_column_by_name.py
  2. #encoding=utf-8
  3. #!/usr/bin/env python3
  4. import csv
  5. import sys
  6. input_file=sys.argv[1]
  7. output_file=sys.argv[2]
  8. my_columns=['Invoice Number','Purchase Date'] #这里实际上是第2,5列。
  9. my_columns_index=[]
  10. with open(input_file,'rb') as csv_in_file:
  11. with open(output_file,'wb') as csv_out_file:
  12. filereader=csv.reader(csv_in_file)
  13. filewriter=csv.writer(csv_out_file)
  14. header=next(filereader,None)
  15. for index_value in range(len(header)):
  16. if header[index_value] in my_columns:
  17. my_columns_index.append(index_value) #将my_columns写入第一行。
  18. filewriter.writerow(my_columns)
  19. for row_list in filereader:
  20. row_list_output=[] #集合的值应该是:1,4;这里实际上是第2,5列。
  21. for index_value in my_columns_index: #
  22. row_list_output.append(row_list[index_value])
  23. filewriter.writerow(row_list_output)
  24. #结果
  25. [root@mysql51 python_scripts]# python 7csv_reader_column_by_name.py supplier_data.csv 9output_csv.csv
  26. [root@mysql51 python_scripts]#
  27. [root@mysql51 python_scripts]#
  28. [root@mysql51 python_scripts]# more 9output_csv.csv
  29. Invoice Number,Purchase Date
  30. 001-1001,1/20/2014
  31. 001-1001,1/20/2014
  32. 001-1001,1/20/2014
  33. 001-1001,1/20/2014
  34. 50-9501,1/30/2014
  35. 50-9501,1/30/2014
  36. 50-9505,2/3/2014
  37. 50-9505,2/3/2014
  38. 920-4803,2/3/2014
  39. 920-4804,2/10/2014
  40. 920-4805,2/17/2014
  41. 920-4806,2/24/2014

2.pandas 实现特定标题列的值。

  1. vi 7csv_reader_column_by_name.py
  2. #encoding=utf-8
  3. #!/usr/bin/env python3
  4. import pandas as pd
  5. import sys
  6. input_file=sys.argv[1]
  7. output_file=sys.argv[2]
  8. data_frame=pd.read_csv(input_file)
  9. data_frame_column_by_name=data_frame.loc[:,['Invoice Number','Purchase Date']]
  10. data_frame_column_by_name.to_csv(output_file,index=False)
  11. #结果
  12. python C:\Users\4201.HJSC\PycharmProjects\pythonProject\7csv_reader_column_by_name.py \
  13. C:\Users\4201.HJSC\Desktop\Python_exercise\supplier_data.csv \
  14. C:\Users\4201.HJSC\Desktop\Python_exercise\9output_csv.csv
  15. more 9output_csv.csv
  16. Invoice Number,Purchase Date
  17. 001-1001,1/20/2014
  18. 001-1001,1/20/2014
  19. 001-1001,1/20/2014
  20. 001-1001,1/20/2014
  21. 50-9501,1/30/2014
  22. 50-9501,1/30/2014
  23. 50-9505,2/3/2014
  24. 50-9505,2/3/2014
  25. 920-4803,2/3/2014
  26. 920-4804,2/10/2014
  27. 920-4805,2/17/2014
  28. 920-4806,2/24/2014

3.总结

通过loc函数来选取列值。
data_frame.iloc[:,[0,3]] #取第一列和第四列
data_frame.loc[:,['Invoice Number','Purchase Date']]#取'Invoice Number'列和'Purchase Date'列的值。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号