파이썬/데이터프레임

python(vscode)/데이터프레임 추가/제거/인덱스 초기화

gongdol 2024. 2. 19. 12:45
300x250

1. 코드 작성

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
31
32
33
34
35
36
37
38
39
import random
import pandas as pd
 
ohlcv = {'min_t' : [], 'open':[],'high':[],'low':[],'close':[],'volume':[]}
 
# 1. 랜덤데이터 만들기 
for i in range(10):
        min_t = random.randrange(1000011000)
        open = random.randrange(1000011000)
        high = random.randrange(1000011000)
        low = random.randrange(1000011000)
        close = random.randrange(1000011000)
        volume = random.randrange(1000011000)
                
        # ohlcv['min_time'].append(min_time.strip())
        ohlcv['min_t'].append(int(min_t))
        ohlcv['open'].append(int(open))
        ohlcv['high'].append(int(high))
        ohlcv['low'].append(int(low))
        ohlcv['close'].append(int(close))
        ohlcv['volume'].append(int(volume))
 
#2. 데이터 프레임으로 변환
df = pd.DataFrame(ohlcv, columns=['min_t','open','high','low','close','volume'])
print("/n#2.실행\n",df)
 
#3. 첫줄 데이터 2개 연속 지우기
for i in range(2):
    df.drop(df.index[0], axis=0, inplace=True# inplace=True 는 원본에서 바로 바꿀때 사용한다. 
print("\n#3.실행\n",df) 
 
#4. 마지막줄 데이터 2개 추가하기
for i in range(2): 
    df.loc[df.index[-1+ 1= [i] * 6
print("\n#4.실행\n",df) 
 
#5. 인덱스 리셋하기
df.reset_index(drop=True,inplace=True)
print("\n#5.실행\n",df) 
cs

 

2. 결과

 

300x250