관리 메뉴

Storage Gonie

pandas.Dataframe – 3편 column 추가 방법 본문

데이터 사이언스/Python 데이터분석

pandas.Dataframe – 3편 column 추가 방법

Storage Gonie 2018. 5. 19. 01:54
반응형

 

from pandas import Series, DataFrame
#데이터프레임 생성 
df = DataFrame({"x1":[1,2,3], "x2":[11,22,33], "x3":[111,222,333]}, index=["i1","i2","i3"]) 
print(df) 
""" 
  x1 x2 x3
i1 1 11 111 
i2 2 22 222 
i3 3 33 333 
"""

1. 단일값을 가지는 column 추가

df["x4"] = 6
print(df)
"""
 x1 x2 x3 x4
i1 1 a 111 6
i2 2 b 222 6
i3 3 c 333 6
"""

2. 다른 column을 이용한 column 추가 방법

#Boolean 값을 가지는 column 추가
df["x5"] = df["x1"] > 300
print(df)
"""
 x1 x2 x3 x4 x5
i1 1 a 111 6 False
i2 2 b 222 6 False
i3 3 c 333 6 False
"""
#두 column을 이용하여 새로운 column 추가
df["x6"] = df["x1"] + df["x3"]
print(df)
"""
 x1 x2 x3 x4 x5 x6
i1 1 a 111 6 False 112
i2 2 b 222 6 False 224
i3 3 c 333 6 False 336
"""

2. Series로 column 추가(column값을 변경할때도 사용가능)

add_srs = Series([1001, 2001, 3001, 4001], index=["i1", "i2", "i3", "i4"])
#i4는 존재하지 않으므로 적용이 안됨.
df["x7"] = add_srs
print(df)
"""
    x1  x2   x3  x4     x5   x6    x7
i1   1  11  111   6  False  112  1001
i2   2  22  222   6  False  224  2001
i3   3  33  333   6  False  336  3001
"""
# 부분적으로 값을 가지는 시리즈도 추가 가능하다.
add_srs = Series([2222, 3333], index=["i2", "i3"])
df["x8"] = add_srs
print(df)
"""
    x1  x2   x3  x4     x5   x6    x7      x8
i1   1  11  111   6  False  112  1001     NaN
i2   2  22  222   6  False  224  2001  2222.0
i3   3  33  333   6  False  336  3001  3333.0
"""

3. list로 column추가

add_lst = [4141,1212,3131]
df["x9"] = add_lst
print(df)
"""
    x1  x2   x3  x4     x5   x6    x7      x8    x9
i1   1  11  111   6  False  112  1001     NaN  4141
i2   2  22  222   6  False  224  2001  2222.0  1212
i3   3  33  333   6  False  336  3001  3333.0  3131
"""
 

 

반응형
Comments