【发布时间】:2017-11-10 10:29:50
【问题描述】:
我有两个 csv 文件要操作,然后合并为一个文件。我首先将它们转换为熊猫。一个 pandas 数据框如下所示:
Number Quiz
0 111111145 0
1 111111108 1
2 111111123 1
3 111111114 0
4 111111132 0
另一个是这样的:
Last Name First Name Number Quiz
0 Student1 Student1 111111123
1 Student2 Student2 111111114
2 Student3 Student3 111111132
3 Student4 Student4 111111145
4 Student5 Student5 111111108
我想得到这样的结果:
Last Name First Name Number Quiz
0 Student1 Student1 111111108 1
1 Student2 Student2 111111114 0
2 Student3 Student3 111111123 1
3 Student4 Student4 111111132 0
4 Student5 Student5 111111145 0
但是当我运行我的代码时,我最终得到:
Last Name First Name Number Quiz
0 Student1 Student1 111111108 0
1 Student2 Student2 111111114 1
2 Student3 Student3 111111123 0
3 Student4 Student4 111111132 1
4 Student5 Student5 111111145 0
我不知道为什么。我的代码如下:
import argparse
import sys, re
import numpy as np
import smtplib
from random import randint
import csv
import math
import pandas as pd
parser = argparse.ArgumentParser()
parser.add_argument('-cname', '--c', help = 'column name to copy')
parser.add_argument('-source', '--s', help = 'source file with the column to copy')
parser.add_argument('-target', '--t', help = 'the target file with the names and UINS')
parser.add_argument('-out', '--f', help = 'output file with column copied')
if len(sys.argv)==1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
sourceFile = pd.read_csv(args.s)
targetFile = pd.read_csv(args.t)
print sourceFile
print targetFile
del targetFile[args.c]
sourceFile.sort_values('UIN', ascending = True, inplace = True)
targetFile.sort_values('UIN', ascending = True, inplace = True)
print sourceFile
print targetFile
targetFile[args.c]= sourceFile[args.c]
targetFile.to_csv(args.f, index = False)
print targetFile
【问题讨论】:
标签: python csv sorting pandas dataframe