Python

파이썬 로직, 데이터 컨트롤, 데이터 필터링 정리

m_ah 2018. 6. 7. 19:38



공부하면서 기억하면 좋을 것들이 있을때, 귀찮지 않은 시간에 정리하는 공간




Python 파이썬 로직, 데이터필터링 관련 잡다한 팁



1. numpy 에서 논리적인 계산값을 2개이상 조건으로 골라낼때


np.logical_and(~~~,~~~)

np.logical_or

np.logical_not()




2. if, elif, else 의 general format


>if 

if conditions:

expression


>elif

if conditions:

expression

else :

expression


>else

if conditions:

expression

elif conditions:

expression

else:

expression





3. 이런 것들을 응용해서 pandas dataframe 에 적용시켜 데이터 필터링


>is_bigger=country["area"]>10

>country[is_bigger]


이런 논리의 트릭.










4. 기억해두면 좋을것 같은 코드 : 판다스에서 데이터 필터링 하기


# import data

import pandas as pd

animal=pd.read_csv('animal.csv', index_col = 0)


import numpy as np


# medium: between 10 and 50 : 몸길이가 10-50인 동물 걸러내기


bdlength=animal['length']

between=np.logical_and(bdlength>10, bdlength<50)

medium=animal[between]


print(medium)




5. 또 다른 코드


import numpy as np


for c in np_height :

    print(str(c)+" cm")


for d in np.nditer(np_ball) :

    print(d)





6. Iterrows() 함수 쓰기 



import pandas as pd

animal = pd.read_csv('animal.csv', index_col = 0)


for lab, row in animal.iterrows() :

    print(lab)

    print(row)





7.  Iterrows() 함수 또 다른 예제



import pandas as pd

animal = pd.read_csv('animal.csv', index_col = 0)


for lab, row in animal.iterrows() :

    print(str(lab)+": "+str(row['body_length']))







8.  판다스 컬럼 추가하기  # for 루프문으로 COLOR 컬럼 추가하기

for lab, row in animal.iterrows() :
    animal.loc[lab, "COLOR"] = row["color"].upper()
    
print(animal)