2016-08-26 4 views
3

CSV 파일을 가져 와서 행을 분할하여 캐스케이드해야합니다. 입력 된 CSV는 다양한 양의 열 (항상 짝수)을 가질 수 있지만 항상 같은 방식으로 분할됩니다. 일부 파일의 경우 출력이 500,000 행이 될 것이기 때문에 팬더를 사용하기로 결정 했으므로 속도가 빨라질 것이라고 생각했습니다.데이터 프레임의 동적 분할 행

입력 :

h1 h2 h3 h4 h5 h6 
A1 A2 A3 A4 A5 A6 
B1 B2 B3 B4 B5 B6 

예상 출력

h1 h2 h3 h4 h5 h6 
A1 A2 
A1 A2 A3 A4 
A1 A2 A3 A4 A5 A6 
B1 B2 
B1 B2 B3 B4 
B1 B2 B3 B4 B5 B6 

나는 당신이 가까이 볼 수 있습니다 (일부 검색과 내 자신의 편집에서 함께 자갈길) 아래의 코드를 사용했지만, 꽤 내가 필요한 것. 제공

importFile = pd.read_csv('file.csv') 
df = df_importFile = pd.DataFrame(importFile) 

index_cols = ['h1'] 
cols = [c for c in df if c not in index_cols] 

df2 = df.set_index(index_cols).stack().reset_index(level=1, drop=True).to_frame('Value') 

df2 = pd.concat([pd.Series([v if i % len(cols) == n else '' 
         for i, v in enumerate(df2.Value)], name=col) 
      for n, col in enumerate(cols)], axis=1).set_index(df2.index) 


df2.to_csv('output.csv') 

h1 h2 h3 h4 h5 h6 
A1 A2 
A1  A3 
A1   A4 
A1    A5 
A1     A6 

답변

3
# take number of columns and divide by 2 
# this is the number of pairs 
pairs = df.shape[1] // 2 

# np.repeat takes the number of rows and returns an object to slice 
# the dataframe array df.values... then slice... result should be 
# of length pairs * len(df) 
a = df.values[np.repeat(np.arange(df.shape[0]), pairs)] 

# row values to condition with as column vector 
dim0 = (np.arange(a.shape[0]) % (pairs))[:, None ] 

# column values to condition with as row vector 
dim1 = np.repeat(np.arange(pairs), 2) 

# boolean mask to use in np.where generated 
# via the magic of numpy broadcasting 
mask = dim0 >= dim1 

# QED 
pd.DataFrame(np.where(mask, a, ''), columns=df.columns) 

enter image description here

+0

. 입력 파일의 모든 행을 롤백해야합니다. – mrh5028

+0

@ mrh5028 unftated – piRSquared

+0

완벽하게 일했습니다! 이제 정확히 무슨 일이 일어나는지 이해하려고 노력합니다. – mrh5028

3

이 시도 다음이 작동하지만, 첫 번째 두 행 안타

dfNew = pd.DataFrame() 
ct = 1 
while ct <= df.shape[1]/2 : 
    dfNew = dfNew.append(df[df.columns[:2*ct]]) 
    ct +=1 

dfNew.sort_values(['h1'], ascending=[True]).reset_index(drop=True).fillna("") 
print df 

    h1 h2 h3 h4 h5 h6 
0 A1 A2     
1 A1 A2 A3 A4   
2 A1 A2 A3 A4 A5 A6 
3 B1 B2     
4 B1 B2 B3 B4   
5 B1 B2 B3 B4 B5 B6 
관련 문제