업데이트 갱신 전체 dataframe를 교체 :(파이썬 3.4 팬더를) 다른 (덮어 쓰기)와
나는 다음 않았다을하며 일 : 1. 교체 한 경우 아래 참조 (-경우의 elif - 다른 사람과 경우-ELIF 구조). 2. 문자열로 십이 평가 (예하는 dec == '1'대신하는 dec == 1)
if len(SframeDup.index) > 0 and dec == '1':
SframeDup.to_csv('NWEA CSVs/Students/StudentDuplicates.csv', sep=',')
print ("%d instances of repeated student IDs detected." % len(SframeDup.index))
print ("See StudentDuplicates.csv for duplicates.")
print ("\nThis program will now stop.")
raise SystemExit
#quit() and exit() work too, but only in the editor
#doing this in Ipython Notebook will restart the kernal and require
#re-running and re-compiling preceeding code
elif len(SframeDup.index) >0 and dec == '2':
print ("%d instances of repeated student IDs detected." % len(SframeDup.index))
print ("See StudentDuplicates.csv for duplicates.")
Sframe['dup_check_1'] = Sframe.duplicated(cols = ['TermName', 'SchoolName', 'StudentID'], take_last = False)
Sframe['dup_check_2'] = Sframe.duplicated(cols = ['TermName', 'SchoolName', 'StudentID'], take_last = True)
Sframe = Sframe[(Sframe['dup_check_1'] == False) & (Sframe['dup_check_2'] == False)]
del Sframe['dup_check_1'], Sframe['dup_check_2']
else:
print ("No duplicates found. Oh yeah!")
업데이트 : 나는 내 능력의 최선을 "에 이사"한 비록
가능한 한 최선을 다해 문서화하고 싶었습니다. 나는 2 세트의 코드를 붙이고있다. 첫 번째는 if-elif를 사용하려고 시도하지만 Sframe이 중복을 제거하지 못하게합니다. 두 번째는 중복을 성공적으로 생략했으나 그렇게하려면 if-elif를 제거해야했습니다.
import pandas as pd
import numpy as np
import glob
import csv
import os
import sys
path = r'NWEA CSVs/Students/Raw'
allFiles = glob.glob(path + "/*.csv")
Sframe = pd.DataFrame()
list = []
for file in allFiles:
sdf = pd.read_csv(file,index_col=None, header=0)
list.append(sdf)
Sframe = pd.concat(list,ignore_index=False)
Sframe.to_csv('NWEA CSVs/Students/OutStudents.csv', sep=',')
Sframe["TermSchoolStudent"]=Sframe["TermName"]+Sframe["SchoolName"]+\
Sframe["StudentID"].map(str)
SframeDup = Sframe[Sframe.duplicated("TermSchoolStudent") == True]
if len(SframeDup.index) > 0:
SframeDup.to_csv('NWEA CSVs/Students/StudentDuplicates.csv', sep=',')
print ("%d instances of repeated student IDs detected." % len(SframeDup.index))
print ("See StudentDuplicates.csv for duplicates.")
print ("Enter 1 to make corrections and rerun program. \
\nEnter 2 to proceed without repeated student IDs.")
dec = input("-->")
if dec == 1:
print ("This program will now stop.")
print ("See StudentDuplicates.csv for duplicates.")
raise SystemExit
elif dec == 2:
Sframe['dup_check_1'] = Sframe.duplicated(cols = ['TermName', 'SchoolName', 'StudentID'], take_last = False)
Sframe['dup_check_2'] = Sframe.duplicated(cols = ['TermName', 'SchoolName', 'StudentID'], take_last = True)
Sframe = Sframe[(Sframe['dup_check_1'] == False) & (Sframe['dup_check_2'] == False)]
del Sframe['dup_check_1'], Sframe['dup_check_2']
print (len(Sframe))
출력 : 2840
import pandas as pd
import numpy as np
import glob
import csv
import os
import sys
path = r'NWEA CSVs/Students/Raw'
allFiles = glob.glob(path + "/*.csv")
Sframe = pd.DataFrame()
list = []
for file in allFiles:
sdf = pd.read_csv(file,index_col=None, header=0)
list.append(sdf)
Sframe = pd.concat(list,ignore_index=False)
Sframe.to_csv('NWEA CSVs/Students/OutStudents.csv', sep=',')
Sframe["TermSchoolStudent"]=Sframe["TermName"]+Sframe["SchoolName"]+\
Sframe["StudentID"].map(str)
SframeDup = Sframe[Sframe.duplicated("TermSchoolStudent") == True]
if len(SframeDup.index) > 0:
SframeDup.to_csv('NWEA CSVs/Students/StudentDuplicates.csv', sep=',')
print ("%d instances of repeated student IDs detected." % len(SframeDup.index))
print ("See StudentDuplicates.csv for duplicates.")
Sframe['dup_check_1'] = Sframe.duplicated(cols = ['TermName', 'SchoolName', 'StudentID'], take_last = False)
Sframe['dup_check_2'] = Sframe.duplicated(cols = ['TermName', 'SchoolName', 'StudentID'], take_last = True)
Sframe = Sframe[(Sframe['dup_check_1'] == False) & (Sframe['dup_check_2'] == False)]
del Sframe['dup_check_1'], Sframe['dup_check_2']
print (len(Sframe))
출력 : 2834
**
- 오래된 물건 :
** 나는 새로운 프로그래머로서 나에게는 분명하지 않은 대답으로 간단한 질문이라고 생각한다. 기본적으로, 나는 데이터 프레임 (Sframe)을 가지고 있고 내 프로그램은 그것을 위해 중복을 검사한다. 사용자가 프로그램이 복제본없이 진행해야한다고 지시하면 데이터 프레임에서 중복 (및 고유 한 값)이 제거되고 Sframe은 중복 제거 된 Sframe과 같게 만들어야합니다 (따라서 원래 Sframe을 수정 된 Sframe으로 대체). 그런 다음 주 프로그램에서 위와 같이 사용자가 "2"를 선택하면 Sframe이 수정 된 버전이어야합니다. 그렇지 않으면 처음부터 중복이 발견되지 않았고 (결과적으로 사용자 입력이 입력되지 않은 경우) 원본 Sframe을 사용해야합니다. 중복은 여기
Import Pandas as pd
Sframe = pd.DataFrame()
, 코드 검사 :
내 코드는 다음과 같이 보입니다. 존재하면 다음이 실행됩니다. 존재하지 않으면 다음을 건너 뛰고 원래 정의 된대로 Sframe이 사용됩니다.
이
중복이 검출되었다 가정 코드 :dec = input("-->")
if dec == 1:
print ("This program will now stop.")
print ("this_file.csv to resolve a problem.")
raise SystemExit
elif dec == 2:
# add "Repeated" field to student with duplicates table. Values="NaN"
SframeDup["Repeated"]="NaN"
# New table joins (left, inner) Sframe with duplicates table (SframeDup) to
# identify all rows of duplicates (including the unique values that had
# duplicates)
SframeWDup=pd.merge(Sframe, SframeDup, on='identifier', how='left')
# Eliminate all repeating rows, including originals as pulled during left join
SframeWODup=SframeWDup[SframeWDup.Repeated_y!="NaN"]
# So here, in my mind, I should be able to just do this and the rest of
# the code should treat replace Sframe with SframeWODup (without the found
# duplicates)...
Sframe = SframeWODup
그러나 그것은 작동하지 않습니다. 나는 중복을 제거하기 위해 2
을 선택한 후 len(Sframe)
을 검사 할 때 중복을 다루기 전에 동일한 번호를 얻었 기 때문에 이것을 안다.
미리 도움을 청하십시오. 이것이 명확하지 않은 경우 명확히 밝힙니다.
업데이트 : Sframe.유형 x 째 TermName 객체
DistrictName 객체
SchoolName 객체
StudentLastName 객체
StudentFirstName 객체
StudentMI 객체
StudentID 객체
,StudentDateOfBirth 객체
StudentEthnicGroup 객체
StudentGender 객체
급 오브젝트
TermSchoolStudent 객체 DTYPE
: 오브젝트
Sframe.head()를 이미지 테이블을 반환 다음 링크에서 :,210 https://drive.google.com/file/d/0B1cr7dwUpr_JR3d0YzlwLWFwQU0/view?usp=sharing
데이터 프레임을 복사 한 다음 'drop_duplicates()'를 호출 할 수 있습니까? –
처음에 시도했지만 문제는 복제 된 원래 값을 유지한다는 것입니다. 내 코드에서 값에 중복 값이 있으면 해당 값과 해당 중복 값을 삭제하려고합니다. –
다음 명령의 출력을 제공 할 수 있습니까? (사용자에게 결정을 내리기 전에) 'Sframe.dtypes' 'Sframe.head()' – Jubbles