2017-03-14 1 views
0

내가 이와 같은 데이터 프레임을 가지고 있다고 가정 해 보겠습니다.판다 데이터 프레임의 값을 확장하는 더 빠른 방법

df = pd.DataFrame( data = np.random.random((10,3)), 
        columns = [ 'Year', 'Var1', 'Var2' ], 
        index = np.arange(10)) 
df.Year = np.repeat([2000, 2001], 5) 

>>> df 
    Year  Var1  Var2 
0 2000 0.811247 0.483376 
1 2000 0.707072 0.514624 
2 2000 0.457840 0.246798 
3 2000 0.000576 0.105618 
4 2000 0.825557 0.044757 
5 2001 0.350272 0.406710 
6 2001 0.176377 0.084755 
7 2001 0.039902 0.510173 
8 2001 0.631718 0.136885 
9 2001 0.441104 0.831035 

나는 2001 년의 값을 가져 와서 2200 년까지 반복하고 싶습니다. 현재이 방법을 사용하고 있습니다. (대용량 데이터 프레임의 경우 느립니다.)

df2001 = df[ df.Year == 2001 ] 
extensionRange = np.arange(2002, 2200 + 1) 
for year in extensionRange: 
    df2001.Year = year 
    df = df.append(df2001) 

>>> df.tail(10) 
    Year  Var1  Var2 
5 2199.0 0.350272 0.406710 
6 2199.0 0.176377 0.084755 
7 2199.0 0.039902 0.510173 
8 2199.0 0.631718 0.136885 
9 2199.0 0.441104 0.831035 
5 2200.0 0.350272 0.406710 
6 2200.0 0.176377 0.084755 
7 2200.0 0.039902 0.510173 
8 2200.0 0.631718 0.136885 
9 2200.0 0.441104 0.831035 

실제 데이터 프레임이 훨씬 크기 때문에이 프로세스를 완료하는 데 약 1 분이 소요됩니다. 이 작업을 수행하는 더 빠른 방법이 있습니까? 아마도 추가하지 않고?

답변

0

추가 할 때마다 값 비싼 새 복사본이 생성됩니다. 한 번에 모든 데이터 프레임을 연결하면 시간이 걸릴 수 있습니다.

new_df = pd.concat([df] * len(np.arange(2002, 2200 + 1))) 

%timeit new_df = pd.concat([df] * len(np.arange(2002, 2200 + 1))) 
100 loops, best of 3: 20.5 ms per loop 

이렇게하면 새 데이터 프레임을 만들 때 시간을 절약 할 수 있지만 연도 열을 변경해야합니다. 즉 단순히 올해 변화 달성 할 수 있으며, 당신은 기본적으로 매년 반복하여 초기 데이터 프레임의 길이를리스트의 목록을 만드는

import itertools 
years = [[year]*len(df) for year in np.arange(2002, 2200 + 1)] 
new_df['Year'] = itertools.chain(*years) 

%timeit new_df['Year'] = itertools.chain(*[[year]*len(df) for year in np.arange(2002, 2200 + 1)]) 
1000 loops, best of 3: 424 µs per loop 

을 따를 때 한 번의 작업으로 달성 될 수있다.

0

NumPy와 타일을 사용하여 반복

df = pd.DataFrame(data = np.random.random((10,3)), 
        columns = ['Year','Var1','Var2'], 
        index = np.arange(10)) 
df.Year = np.repeat([2000, 2001], 5) 

# assign variables 
max_year = 2200 
unique_year = 2000 
rows_each_year = 5 

year_clone_count = max_year - unique_year 
# grab values from input dataframe as numpy arrays, tile values to repeat 
base = df[df.Year == unique_year][['Var1', 'Var2']].values 
extended = np.tile(df[df.Year == unique_year + 1][['Var1', 'Var2']].values.T, 
        year_clone_count).T 

# join non-repeat data with repeated data 
data = np.concatenate((base, extended)) 

# make year column 
year_col = np.repeat(range(unique_year, max_year + 1), 
        rows_each_year) 

# create dataframe 
df_out = pd.DataFrame({'Year': year_col, 
         'Var1': data[:, 0], 
         'Var2': data[:, 1]}) 
관련 문제