공부중 .../파이썬과 R
자료의 입력과 출력
Chelsey
2022. 12. 7. 00:14
728x90
명령어 입력받기
- in R
# readline()
age = readline(prompt = "Enter age: ")
age에 20을 입력하면 mode(age)는 문자열 형태이다. 숫자로 바꾸고 싶다면 as.numeric(age)처리를 해줘야한다.
- in Python
# input()
import datetime
age = input("Enter age: ")
now = datetime.datetime.now()
born_year = now.year - int(age)
print(born_year)
텍스트 파일 읽기
- in R
# .txt
read.table
# .csv
read.csv
#---------------
# 1) data file read
myiris = read.table(datapath.txt, header=T)
# 2) url read
url = read.table("http:// ... ")
# col name
# 1)
col.names = c('Sepal',...)
# 2)
colnames(myiris) = c("..",...)
rownames(myiris) = c("..",...)
# data 조금만 읽기
head(myiris)
head(myiris, 3)
tail(myiris, 3)
- in python
# read csv
import pandas as pd
df1 = pd.read_csv("datapath.csv", header=0, sep=" ", encoding="utf-8")
df2 = pd.read_csv("datapath.txt", header=0, sep=" ", index_col="name")
# df2는 name 열이 인덱스값으로 데이터를 구분해준다.
# data 조금만 읽기
df1.head()
df1.head(3)
# df2의 특정 행 추출
df2.loc["Kim"]
# 위치 인덱스로 추출
df2.iloc[0, :]
텍스트 파일 저장하기
write.table(mtcars, "")
엑셀파일 읽고 저장하기 ( R과 Python)
# R
install.packages("readxl")
library(readxl)
read_excel(~)
# Python
import pandas as pd
data = pd.read_excel(~) # data reading
data.to_excel(~) # data writing
# R
getwd() # 현재 파일 위치
setwd("...") # working directory 설정
boston = read.csv("Boston.csv")
# 경로를 적어주지 않아도 해당 경로에 setwd 되어있으면 바로 파일을 불러올 수 있다.
# Python
import os
import pandas as pd
os.getcwd()
os.chdir("...") # default working directory setting
boston = pd.read_csv("Boston.csv")
문자열
# R
paste # 문자열 합치기
strsplit # 문자열 분리
# Python
str1 + str2 # 문자열 합치기
sentence.split('i') # i를 기분으로 분리한다
728x90