반응형
Python, Pandas : DataFrame의 내용을 텍스트 파일에 기록
나는 이와 같은 pandas DataFrame을 가지고 있습니다.
X Y Z Value
0 18 55 1 70
1 18 55 2 67
2 18 57 2 75
3 18 58 1 35
4 19 54 2 70
이런 식으로이 데이터를 텍스트 파일에 쓰고 싶습니다.
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
나는 같은 것을 시도했다
f = open(writePath, 'a')
f.writelines(['\n', str(data['X']), ' ', str(data['Y']), ' ', str(data['Z']), ' ', str(data['Value'])])
f.close()
하지만 작동하지 않습니다. 어떻게해야합니까?
np.savetxt
np 속성을 사용 하고 액세스 할 수 있습니다 .values
.
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')
수율 :
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
또는 to_csv
:
df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep=' ', mode='a')
참고 np.savetxt
당신은 추가 모드로 생성 된 파일 핸들을 전달해야 할 것이다.
당신은 사용할 수 있습니다 pandas.DataFrame.to_csv ()를 , 모두 설정 index
과 header
에를 False
:
In [97]: print df.to_csv(sep=' ', index=False, header=False)
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
pandas.DataFrame.to_csv
파일에 직접 쓸 수 있습니다. 자세한 내용은 위에 링크 된 문서를 참조하세요.
파티에 늦음 : 이것을 시도하십시오>
#pd: your pandas dataframe
base_filename = 'Values.txt'
with open(os.path.join(WorkingFolder, base_filename),'w') as outfile:
pd.to_string(outfile)
#Neatly allocate all columns and rows to a .txt file
이를 수행하는 현재 가장 좋은 방법은 다음을 사용하는 것입니다 df.to_string()
.
with open(writePath, 'a') as f:
f.write(df.to_string(header = False, index = False))
다음을 출력합니다.
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
This method also lets you easily choose which columns to print with the columns
attribute and lets you keep the column, index labels if you wish.
참고URL : https://stackoverflow.com/questions/31247198/python-pandas-write-content-of-dataframe-into-text-file
반응형
'IT TIP' 카테고리의 다른 글
ISO C ++ 표준을 준수하는 사용자 정의 new 및 delete 연산자를 어떻게 작성해야합니까? (0) | 2020.12.01 |
---|---|
Ansible-디렉토리의 경우 모드 755, 파일의 경우 재귀 적으로 644 (0) | 2020.11.30 |
C # /. NET에서 경로와 파일 이름을 결합하는 가장 좋은 방법은 무엇입니까? (0) | 2020.11.30 |
C # ASP.NET TLS를 통해 이메일 보내기 (0) | 2020.11.30 |
함수형 프로그래밍의 맥락에서 구성 가능성은 무엇을 의미합니까? (0) | 2020.11.30 |