여러 열과 큰 숫자가있는 열이있는 txt 파일이 있는데 파이썬을 통해 읽고 csv로 출력하면 숫자가 변경되고 중요한 정보가 손실됩니다. txt 파일의 예 :
Identifier
12450006300638672
12450006300638689
12450006300638693
csv 출력 예 :
Identifier Changed_format_in_csv
1.245E+16 12450006300638600
1.245E+16 12450006300638600
1.245E+16 12450006300638600
큰 숫자를 변경하지 않고 파일을 csv로 출력 할 수있는 방법이 있습니까? 문자열과 숫자 데이터 유형이 혼합 된 다른 열이 많이 있지만 모든 것을 문자열로 출력 할 수 있다면 괜찮을 것이라고 생각했습니다.
이것이 내가 시도한 것입니다.
import pandas as pd
file1 = 'file.txt'
df = pd.read_csv(file1, sep="|", names=['Identifier'], index_col=False, dtype=str)
df.to_csv('file_new.csv', index=False)
csv 파일이 txt 파일처럼 출력되기를 원합니다. dtype = str 설정이 도움이되기를 바랐지만 그렇지 않습니다. 어떤 도움을 주시면 감사하겠습니다.
단편:
이 문제는 pandas가 'file.txt'의 내용을 해석하는 데이터 유형과 관련이 있다고 생각합니다. 시도해 볼 수 있습니다.
df = df.assign(Identifier=lambda x: x['Identifier'].astype(int))
긴 이야기:
이 콘텐츠로 file.txt를 만들었습니다.
12450006300638672
12450006300638689
12450006300638693
pandas v0.23.3을 사용하여 다음과 같이 표시된 코드로 문제를 재현 할 수 없습니다.
>>> import pandas as pd
>>> df = pd.read_csv('file.txt', sep="|", names=['Identifier'], index_col=False, dtype=str)
>>> df.to_csv('file_new.csv', index=False)
>>> print(df)
Identifier
0 12450006300638672
1 12450006300638689
2 12450006300638693
>>> exit()
$ cat file_new.csv
Identifier
12450006300638672
12450006300638689
12450006300638693
하지만 대신 pd.read_csv (..., dtype = float) 를 사용하여 문제를 재현 할 수 있습니다 .
>>> import pandas as pd
>>> df = pd.read_csv('file.txt', sep="|", names=['Identifier'], index_col=False, dtype=float)
>>> df.to_csv('file_new.csv', index=False)
>>> print(df)
Identifier
0 1.245001e+16
1 1.245001e+16
2 1.245001e+16
>>> exit()
$ cat file_new.csv
Identifier
1.2450006300638672e+16
1.2450006300638688e+16
1.2450006300638692e+16
정수가 부동 숫자로 해석되는 경우 인 것 같습니다. 어떤 이유로 정수로 해석 할 수없는 경우 다음과 같이 할 수 있습니다.
>>> import pandas as pd
>>> df = pd.read_csv('file.txt', sep="|", names=['Identifier'], index_col=False, dtype=float)
>>> print(df)
Identifier
0 1.245001e+16
1 1.245001e+16
2 1.245001e+16
>>> df = df.assign(Identifier=lambda x: x['Identifier'].astype(int))
>>> print(df)
Identifier
0 12450006300638672
1 12450006300638688
2 12450006300638692
>>> df.to_csv('file_new.csv', index=False)
>>> exit()
$ cat file_new.csv
Identifier
12450006300638672
12450006300638688
12450006300638692
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다