반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/11   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Tags
more
Archives
Today
Total
관리 메뉴

비전공개미 개발노트

[Python] Pandas 기본출력 본문

프로그래밍/Python

[Python] Pandas 기본출력

비전공개미 2022. 12. 1. 19:52
반응형
SMALL
# Pandas
import pandas as pd


# Series
s = pd.Series([1, 0, -4, 6, -7, -3, 5, 3, -9, 2])
print(s)
print(type(s))
print(s.index)
print(s.values)
print(type(s.values))

s.index = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(s)

# 값과 index를 같이 출력 / ([값], [인덱스])
s = pd.Series([1, 0, -4, 6, -7, -3, 5, 3, -9, 2], ["a", "f", "c", "d", "e", "b", "g", "h", "i", "j"])
print(s)
print(s.index)

# 값 하나 꺼내기
print(s[0])
print(s["a"])
print(s.a)

print(s[0:5])       # 0번째~5번째전까지(5번은 미포함)
print(s["a":"b"])   # a부터 b까지 포함★(숫자표현과 다름)

dict = {"a":10, "b":20, "c":30}
print(type(dict))
ss = pd.Series(dict)
print(ss)
print(type(ss))
print(ss[1])
print(ss["b"])


# DataFrame
# Dictionary -> DataFrame
d = {
        "name":["kim","lee","hong","park"],
        "age":[20, 30, 25, 40],
        "tel":["1111-2222", "2222-2222", "2222-1111", "1111-3333"]
    }
print(type(d))
df = pd.DataFrame(d)
print(type(df))
print(df)
print(df.index)     #index값을 추출
print(df.columns)   #column값만 추출
print(df.values)    #데이터를 추출

df.index.name = "Num"
df.columns.name = "User"
print(df)
print(df.index)
print(df.columns)


# Numpy -> DataFrame
import numpy as np

n = np.array([
        ['kim', 20, '1111-2222'],
        ['lee', 30, '2222-2222'],
        ['hong', 25, '2222-1111'],
        ['park', 40, '1111-3333']
    ])
print(type(n))
df = pd.DataFrame(n)
print(df)
df.index = ["a", "b", "c", "d"]
df.columns = ["name", "age", "tel"]
print(df)

df = pd.DataFrame(n, index = ["a","b","c","d"], columns = ["name","age","tel"])
print(df)
print(df.describe())
#        name age        tel
# count     4   4          4    #갯수
# unique    4   4          4    #중복되지않는값
# top     kim  20  1111-2222    #맨위의 값
# freq      1   1          1

desc = df.describe()
print(desc.index)
print(desc.columns)
print(desc["name"])     #name에 있는 열 4 4 kim 1 출력됨
print(desc.name)        #위와동일
print(desc["name"]["count"])
print(desc["name"][0])
print(desc["name"].count)
print(type(desc["name"]))

print("-----------------------------------")

print(df[["name", "tel"]])  #name, tel만 꺼내온다(2차원 배열)
print(df[:][:])
print(df[:2])
print(df[:2][:1])
# print(df["a"])  #에러

df["address"] = ["서울","인천","안산","수원"]
df["adult"] = df["age"] >= "30"         #True, False의 값이 들어감
df["age"][0] = 40                       #각각의 데이터 수정가능
df["adult"][0] = True
print(df)
print(df.dtypes)

del df["adult"]     #del -- 컬럼삭제
print(df)

df.index = ["A","B","C","D"]            #컬럼 갯수에 맞춰야함
# df.index = ["A","B","C","D","E"]      #에러
df = df.reindex(["A","B","C","D","E"], fill_value=0)  #추가로 더 넣을 수 있다 / fill_value -- NaN값을 설정
df = df.reset_index()
print(df)


s = pd.Series(range(4), index = ["a","c","d","b"])
# s = s.sort_index()
s = s.sort_index(ascending=False)
# s = s.sort_values()
s = s.sort_values(ascending=False)
print(s)

df = pd.DataFrame(np.arange(16).reshape(4, 4), 
                  index = [3, 2, 4, 1], columns = ["b","d","a","c"])
# df = df.sort_index()        #index 정렬
df = df.sort_index(axis=1)    #column 정렬
df = df.sort_values(by="a")   #"a"를 기준으로 정렬
df = df.sort_values(by="a", ascending=False)    #"a"를 기준으로 내림차순 desc
df = df.sort_values(by=["a","b"])   #a로 정렬하고 b로 정렬한다(sql order by문과 비슷)
print(df)


# loc iloc
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(a)
# print(a[0,0])     #error
print(a[0][0])      #0행 0열(인덱싱)
print(a[0:2][0:2])  
print(a[0])
print(a[:2])
print(a[::-1][::-1])

b = np.array(a)
print(b[0][0])
print(b[0:2][0:2])
print(b[0])
print(b[:2])
print(b[0:2, 0:2])      #0,1행 0,1열
print(b[2, 2])

c = pd.DataFrame(a, columns=["A","B","C"], index=["a","b","c"])
print(c)
# print(c[0][0])      #error
print(c["A"][0])
print(c["A"]["a"])
print(c[0:2][0:2])
# print(c[0])         #error
print(c[:2])
# print(c[0:2, 0:2])  #error

# iloc
print(c["A"][0])
print(c[["A", "C"]])
print(c[["A", "B"]][0:2])
# print(c[["A" : "B"]])   #error(나중에 loc에서 가능)

# print(c.loc([0][0]))
# print(c.loc[0, 0])    #error
print(c.iloc[0, 0])     #iloc는 가능
print(c.loc["a"]["A"])
# print(c.loc[1, 1])    #error
# print(c.loc[:2, :2])  #error
print(c.loc["a":"b"])
print(c.loc["a":"b", :])
print(c.loc["a":"b", :"B"])     #error(index를 문자로 지정해줘서 숫자error)
# print(c.loc[:-1, :-1])        #error
print(c.loc["a", "B"])      #a행의 B열


d = pd.DataFrame(a, columns=["A","B","C"])
print(d)
print(d.loc[:2, :"B"])
# print(d.loc[1, 1])        #error
e = pd.DataFrame(a)
print(e)
print(e.loc[:1, :1])

# iloc
print(c.iloc[1, 1])
# print(c.iloc["b", "B"])     #error (iloc는 이름으로 호출x 숫자만 사용가능)
print(e.iloc[1, 1])
print(c.iloc[:2, :2])
print(c.iloc[:-1, :-1])
print(c.iloc[::-1, ::-1])
print(c.iloc[0][0])         #loc는 index값(문자)을 지정해주면 숫자로 호출이 안되지만 iloc는 가능

c["D"] = [11, 12, 13]       #열을 추가
c.loc[:, "E"] = [20, 21, 22]            #열 추가
c.loc["d"] = [30, 31, 32, 33, 34]       #행 추가
print(c)

del c["D"]
c = c.drop("d")     #기본 axis=0  행
# c = c.drop("E")    #axis를 안주고 열을 지우면 오류가 남(이름도 정확히 맞아야됨)
c = c.drop("E", axis=1)
print(c)

# e[3] = [10, 11, 12]
# # e.iloc[:, 4] = [20, 21, 22]        #error
# # e.iloc[3, :] = [30, 31, 32, 33]    #error
# print(e)

print("-------------------------")

df = pd.DataFrame([["kim", 20, "1111-1111"],
                   ["lee", 30, "1111-2222"],
                   ["park", 40, "1111-3333"],
                   ["jung", 25, "1111-4444"],
                   ["hong", 35, "1111-5555"]], 
                   columns=["name", "age", "tel"])
print(df)
print(df["name"])
print(df["name"][1])
print(df.iloc[:, 0])
print(df.iloc[1, 0])        #1열에 0번째
print(df.loc[:, "name"])
print(df.loc[1, "name"])    #1행의 name열의 값

print(df[["name", "tel"]])
print(df.iloc[:, [0,2]])
print(df.loc[:, ["name", "tel"]])

# print(df[[0:2]])    #error
print(df.iloc[:, 0:2])
print(df.loc[:, "name":"age"])

print("-----------------------------------------")

# boolean Indexing
print(df.loc[df["age"] > 30, ["name", "age"]])
print(df.loc[df["name"] == "kim", "name":"tel"])
print(df.loc[(df["age"] >= 30) & (df["age"] <= 40), "name":"age"])

print("----------------------------------------")

# 결측값 대체
df["address"] = ["서울", "", np.NaN, "인천", "수원"]
df.loc[df["address"] == "", "address"] = "안산"
df.loc[df["address"] == np.NaN, "address"] = "평택"
df.loc[df["address"].isnull(), "address"] = "평택"    #np.NaN을 찾으려면 isnull()함수 사용

# 결측값 삭제
df["income"] = [None, 2000, 3000, np.NaN, 4000]
df.loc[5, :] = [np.NaN, np.NaN, np.NaN, np.NaN, np.NaN]
# df = df.dropna(how="any")    #any - 하나라도 NaN인 항목을 다 지워라(데이터가 너무 많이 지워짐)
# df = df.dropna(how="all")    #all - 전체값이 NaN인 항목을 지운다(부분만 NaN인 데이터 보호)
# df.dropna(how="all", inplace=True)

# df.fillna(value=0, inplace=True)    #NaN인 값을 value값으로 채운다
# df.fillna(value=np.mean(df["income"]), inplace=True)
# df["income"].fillna(value=np.mean(df["income"]), inplace=True)

# del df["income"]
# df = df.drop("income", axis=1)

# df = df.drop(df.loc[df["income"].isnull(), "income"].index, axis=0)
# df = df.drop(["address", "income"], axis=1)


# 전치
# print(df)
# print(df.T)
# print(df.transpose())


# 분석용 함수들
df = pd.DataFrame([["kim", 90, 87, 55],
                   ["lee", 80, 70, 85],
                   ["park", 92, 95, np.NaN],
                   ["jung", 75, 85, 90],
                   ["hong", 80, 90, 82], 
                   ["kang", np.NaN, 70, np.NaN]],
                   columns=["name", "kor", "eng", "mat"])
# print(df)
# print(df.count())
# print(df.count(axis=1))
# print(df.min())
# print(df.max())
# print(df.mean())
# print(df.sum())

# df["tot"] = df.sum(axis=1)
# df = df.loc[:, "kor":"mat"].fillna(value=0)
# df["avg"] = df.loc[:, "kor":"mat"].mean(axis=1)

# print(df.median())
# print(df.mad())     #편차
# print(df.var())     #분산
# print(df.std())     #표준편차
# print(df.cumsum())
# print(df.loc[:, "kor":"mat"].cumprod())

# print(df.loc[:, "kor":"mat"].idxmin())
# print(df.loc[:, "kor":"mat"].idxmax())


# 상관관계(값이 1에 가까울수록 확률이 높다)
print(df["kor"].corr(df["eng"]))    #국어를 잘하면 영어를 잘하는가?
print(df["kor"].corr(df["mat"]))    #국어를 잘하면 수학을 잘하는가?

df.fillna(value=0, inplace=True)
df["avg"] = df.loc[:, "kor":"mat"].mean(axis=1)

# 값이 클수록 상관관계가 높다
print(df["kor"].corr(df["avg"]))
print(df["eng"].corr(df["avg"]))
print(df["mat"].corr(df["avg"]))

print(df["kor"].cov(df["avg"]))
print(df["eng"].cov(df["avg"]))
print(df["mat"].cov(df["avg"]))

print(df)
print(df.sort_index(ascending=False))
print(df.sort_values(by="kor"))
print(df.sort_values(by="avg", ascending=False))

print(df["name"].unique())      #중복안되는 값 찾기
print(df['name'].value_counts())
print(df["kor"].isin([50, 60, 70, 80, 90]))     #isin값 안에 포함되어있으면 True

print("-------------------------------------")

# UDF 적용
df = pd.DataFrame(np.random.randn(4, 3), columns=["a", "b", "c"], 
                  index=["kim", "lee", "park", "jung"])
print(df)
def func(a):
    return a.max() - a.min()
print(df.apply(func, axis=0))
print(df.apply(lambda x : x.max()-x.min(), axis=1))     #lambda 매개변수 : return값
반응형
LIST

'프로그래밍 > Python' 카테고리의 다른 글

[Python] seaborn 기본연습  (0) 2022.12.01
[Python] matplotlib.pyplot, seaborn 기본연습  (0) 2022.12.01
[Python] Numpy 기본출력  (0) 2022.12.01
python 5일차 - 성적 관리 프로그램  (0) 2022.09.02
python 5일차 - NumPy  (0) 2022.09.02
Comments