Exemple #1
0
    "job": "Trash"
}, {
    "name": "Lee",
    "age": 30,
    "job": "Animal"
}, {
    "name": "Park",
    "age": 40,
    "job": "Streamer"
}, {
    "name": "Ryu",
    "age": 50
}]
df = pd.DataFrame.from_dict(friends)
print("New DataFrame:")
mymodule.printline(df)

# 1) 생성하기
df['salary'] = 123
print("1) 생성하기")
mymodule.printline(df)

# 2) 특정 column의 조건에 따라 생성될 column를 제어하기
# numpy 사용이 필요하다.
import numpy as np
df['salary'] = np.where(df['job'] != 'Trash', 250, 'no')
print("2) 특정 column의 조건에 따라 생성될 column를 제어하기")
mymodule.printline(df)

# 예제
exam_list = [["John", 10, 20], ["Kim", 30, 40], ["Ryu", 50, 60],
Exemple #2
0
}, {
    "name": "Bob",
    "age": 30,
    "birthday": "July",
    "job": "teacher"
}, {
    "age": 27,
    "job": "streamer",
    "name": "Girl"
}]

# 1. list (dictionary를 element로 가지는) 을 이용해 만들기
# Dataframe은 dictionary의 list를 통해 만들 수 있다.
# Column의 순서는 list 내 첫 번째 element인 dictionary의 순서를 따르는 듯 하다.
dataframe = pandas.DataFrame(friend_dict_list)
mymodule.printline(dataframe)
dataframe = pandas.DataFrame.from_dict(friend_dict_list)
mymodule.printline(dataframe)

# Column 순서를 강제로 바꾼다면? --> element들의 순서까지 자동으로 바뀌진 않는다.
dataframe.columns = ["name", "age", "job", "birthday"]
mymodule.printline(dataframe)

# 2. OrderedDict를 이용해 만들기
# dict 대신 OrderedDict를 사용함으로써 column의 순서를 제어할 수도 있다.
# 단, 이 경우에는 빈 칸을 만들 수 없다.
# OrderedDict를 만들 때, list의 length가 다르면 안 되기 때문이다.
# 즉, 각 series의 element 개수가 같아야 한다.
from collections import OrderedDict
friend_ordered_dict = OrderedDict([("age", [25, 30, 27]),
                                   ("name", ["John", "Bob", "Girl"]),
Exemple #3
0
import pandas
import mymodule

# 1강. Dataframe & Series

# dataframe은 pandas의 class입니다.
# dataframe은 default는 csv파일에서 읽어옵니다.
dataframe = pandas.read_csv("temp.csv")
mymodule.printline(dataframe)

# dataframe의 일부만을 출력 가능합니다.
# head는 처음부터, tail은 끝줄부터 셉니다.
mymodule.printline(dataframe.head(2))
mymodule.printline(dataframe.tail(2))
mymodule.printline(dataframe.head())
mymodule.printline(dataframe.tail())

# series는 pandas의 class입니다.
# series는 list로 만듭니다.
s1 = pandas.core.series.Series([1, 2, 3])
s2 = pandas.core.series.Series(['one', 'two', 'three'])
mymodule.printline(s1)
mymodule.printline(s2)

# dataframe은 series의 집합입니다.
# dataframe은 series를 dictionary로 묶어서 만듭니다.
dataframe = pandas.DataFrame(data=dict(num = s1, word = s2))
mymodule.printline(dataframe)

# 각 column을 선택하는 두 가지 방법
print(dataframe.word)
Exemple #4
0
# 중복된 row 삭제하기.

student_list = [
    ["Kim", "CS", "male"],  # 중복 1 
    ["Park", "CS", "male"],
    ["Choi", "EE", "male"],
    ["Ryu", "Physics", "male"],  # 중복 2
    ["Lee", "Economics", "female"],
    ["Kim", "CS", "male"],  # 중복 1
    ["Jenny", "CS", "female"],
    ["Kim", "CS", "male"],  # 중복 1
    ["John", "Physics", "male"],
    ["Ryu", "Physics", "male"]  # 중복 2
]
df = pd.DataFrame(student_list, columns=["name", "major", "sex"])
mymodule.printline(df)

# 1) duplicated method로, 어느 line이 중복인지를 확인 가능.
print("1) duplicated method로, 어느 line이 중복인지를 확인 가능.")
mymodule.printline(df.duplicated())

# 2) drop_duplicates method로, 중복된 row를 "모두" 제거 가능.
print("2) drop_duplicates method로, 중복된 row를 모두 제거 가능.")
mymodule.printline(df.drop_duplicates())

# 하나의 column만 같은 경우에만 제거하려면? (이름이 같은 경우)
student_list = [
    ["Kim", "CS", "male"],  # 중복 1 
    ["Park", "CS", "male"],
    ["Choi", "EE", "male"],
    ["Ryu", "Physics", "male"],  # 중복 2
Exemple #5
0
    "job": "Trash"
}, {
    "name": "Lee",
    "age": 30,
    "job": "Animal"
}, {
    "name": "Park",
    "age": 40,
    "job": "Streamer"
}, {
    "name": "Ryu",
    "age": 50
}]
dataframe = pandas.DataFrame.from_dict(friends)
print("DataFrame:")
mymodule.printline(dataframe)

# 1) row_index 로 row select하기
sub_df = dataframe[1:3]
print(" 1) row_index 로 row select하기")
mymodule.printline(sub_df)

# 2) row_index 로 불연속적인 row select하기
sub_df = dataframe.loc[[0, 3]]
print(" 2) row_index 로 불연속적인 row select하기")
mymodule.printline(sub_df)

# 3) column 조건에 따라 row select하기
sub_df = dataframe[dataframe.age > 35]
print(" 3) column 조건에 따라 row select하기")
mymodule.printline(sub_df)
Exemple #6
0
        "name": "Lee",
        "age": 30,
        "job": "Animal"
    },
    {
        "name": "Park",
        "age": None,
        "job": "Streamer"
    },  # 이렇게 None을 줄 수도 있고
    {
        "name": "Ryu",
        "age": 50
    }  # 그냥 비워서 None을 줄 수도 있다.
]
df = pd.DataFrame.from_dict(friends)
mymodule.printline(df)

# 1) 각 column별로 NaN이 있는지 확인하는 방법

# 1-1) df.info() 로 확인하기
# non-null 값의 개수를 column 별로 출력해준다.
mymodule.printline(df.info())

# 1-2) df.isna() 로 확인하기  ( => 완전히 똑같은 기능 isnull() )
# NaN value 의 경우 True 이다.
mymodule.printline(df.isna())
mymodule.printline(df.isnull())

# 2) fillna() 메소드로 NaN 값 바꾸기
# age column에서 NaN값이 있으면, 0으로 바꿔줘
temp_df = df
Exemple #7
0
import pandas as pd
import mymodule

# 8. Group

student_list = [["Kim", "CS", "male"], ["Park", "CS", "male"],
                ["Choi", "EE", "male"], ["Ryu", "Physics", "male"],
                ["Lee", "Economics", "female"], ["Jenny", "CS", "female"],
                ["John", "Physics", "male"]]

df = pd.DataFrame(student_list, columns=["name", "major", "sex"])
mymodule.printline(df)

# 1) group 이라는 class를 사용할 수 있습니다.
groupby_major = df.groupby("major")

print(groupby_major.groups)  # dictionary입니다.
print(type(groupby_major.groups))

print(groupby_major.name)
print(groupby_major.sex)

for name, group in groupby_major:  # 시각적으로 좋은 print를 위해
    print(name + " : " + str(len(group)))
    print(group)
    print()

# 2) 학과별 인원을 dataframe으로 만들고 싶어요.
df_major_cnt = pd.DataFrame({'count': groupby_major.size()})
mymodule.printline(df_major_cnt)