Flux in Julia/Learning Julia (Intro_to_Julia_DFs)
09. reshaping(한글)
딥스탯
2018. 10. 15. 10:58
Introduction to DataFrames¶
Bogumił Kamiński, Apr 21, 2018
출처¶
함께보기¶
- https://deepstat.tistory.com/69 (01. constructors)(in English)
- https://deepstat.tistory.com/70 (01. constructors)(한글)
- https://deepstat.tistory.com/71 (02. basicinfo)(in English)
- https://deepstat.tistory.com/72 (02. basicinfo)(한글)
- https://deepstat.tistory.com/73 (03. missingvalues)(in English)
- https://deepstat.tistory.com/74 (03. missingvalues)(한글)
- https://deepstat.tistory.com/75 (04. loadsave)(in English)
- https://deepstat.tistory.com/76 (04. loadsave)(한글)
- https://deepstat.tistory.com/77 (05. columns)(in English)
- https://deepstat.tistory.com/78 (05. columns)(한글)
- https://deepstat.tistory.com/79 (06. rows)(in English)
- https://deepstat.tistory.com/80 (06. rows)(한글)
- https://deepstat.tistory.com/81 (07. factors)(in English)
- https://deepstat.tistory.com/82 (07. factors)(한글)
- https://deepstat.tistory.com/83 (08. joins)(in English)
- https://deepstat.tistory.com/84 (08. joins)(한글)
- https://deepstat.tistory.com/85 (09. reshaping)(in English)
- https://deepstat.tistory.com/86 (09. reshaping)(한글)
In [1]:
using DataFrames # load package
데이터프레임 모양 바꾸기 (Reshaping DataFrames)¶
넓은 형태에서 긴 형태로 (Wide to long)¶
In [2]:
x = DataFrame(id=[1,2,3,4], id2=[1,1,2,2], M1=[11,12,13,14], M2=[111,112,113,114])
Out[2]:
In [3]:
melt(x, :id, [:M1, :M2]) # id 변수를 먼저 넣고, measure 변수를 넣는다. meltdf는 뷰(view)를 만든다.
Out[3]:
In [4]:
# 추가적으로 행 이름을 지정해 줄 수 있다. (melt와 stack은 같은 역할을 하지만 인자(argument)의 순서가 다르다.
stack(x, [:M1, :M2], :id, variable_name=:key, value_name=:observed) # measure가 먼저오고 id가 나중에 온다. stackdf는 뷰(view)를 만든다.
Out[4]:
In [5]:
# 만일 melt나 stack 함수에 두 번째 인자가 없다면, 모든 다른 행이 두 번째 인자인 것 처럼 실행된다.
# 하지만 measure 변수는 <: AbstractFloat 타입일 때만 선택된다.
melt(x, [:id, :id2])
Out[5]:
In [6]:
melt(x, [1, 2]) # 행 이름 대신에 인덱스(index)를 사용할 수도 있다.
Out[6]:
In [7]:
bigx = DataFrame(rand(10^6, 10)) # 데이터프레임을 만드는 것과 뷰(view)를 만드는 것의 차이를 보기 위해 만듦.
bigx[:id] = 1:10^6
@time melt(bigx, :id)
@time melt(bigx, :id)
@time meltdf(bigx, :id)
@time meltdf(bigx, :id);
In [8]:
x = DataFrame(id = [1,1,1], id2=['a','b','c'], a1 = rand(3), a2 = rand(3))
Out[8]:
In [9]:
melt(x)
Out[9]:
In [10]:
melt(DataFrame(rand(3,2))) # 기본적으로 stack과 melt는 float타입을 value행으로 취급한다.
Out[10]:
In [11]:
df = DataFrame(rand(3,2))
df[:key] = [1,1,1]
mdf = melt(df) # key가 중복되더라도 아무런 메세지 없이 실행된다.
Out[11]:
긴 형태에서 넓은 형태로 (Long to wide)¶
In [12]:
x = DataFrame(id = [1,1,1], id2=['a','b','c'], a1 = rand(3), a2 = rand(3))
Out[12]:
In [13]:
y = melt(x, [1,2])
display(x)
display(y)
In [14]:
unstack(y, :id2, :variable, :value) # key가 하나인 기본적인 unstack
Out[14]:
In [15]:
unstack(y, :variable, :value) # 모든 행이 key로 받아들여진다.
Out[15]:
In [16]:
# 기본적으로 (:id, :variable, :value)가 가정돼있다. 이 경우에는 중복되는 key가 있어서 경고(Warning)을 출력한다.
unstack(y)
Out[16]:
In [17]:
df = stack(DataFrame(rand(3,2)))
Out[17]:
In [18]:
unstack(df, :variable, :value) # key 행이 없으면 unstack이 되지 않는다.