2017-03-17 1 views
0

데이터 프레임이 있습니다. 목록을 다른 열로 추출하려고합니다. 열에서Python에서 요소를 추출하여 새 열을 만듭니다.

df = pd.concat([df[x].astype(str).str.split(',', expand=True) for x in df], 
       axis=1, 
       keys=df.columns).fillna(0) 

MultiIndex 제거 할 수 있습니다 : 당신은 list comprehensionsplitconcat을 사용할 수 있습니다

df = pd.DataFrame({"Q007_A00":["Y","Y","Y","Y","Y"], 
       "Q007_B00": ["N","N","N","N","N"], 
       "Q007_C01": [1,4,5,2,"8,3"], 
       "Q007_C02": ["Text 1","Text 2","Text 3,Text 4,Text 5","Text 4","Text 5,Text 6"]}) 

    Q007_A00 Q007_B00 Q007_C01 Q007_C02 
0 Y   N   1   Text 1 
1 Y   N   4   Text 2 
2 Y   N   5   Text 3,Text 4,Text 5 
3 Y   N   2   Text 4 
4 Y   N   8,3  Text 5,Text 6 

출력

Q007_A00 Q007_B00 Q007_C01 Q007_C01_1 Q007_C02 Q007_C02_1 Q007_C02_2 
Y   N   1  0  Text 1 0   0 
Y   N   4  0  Text 2 0   0 
Y   N   5  0  Text 3 Text 4  Text 5 
Y   N   2  0  Text 4 0   0 
Y   N   8  3  Text 5 Text 6  0 

이 열 이름은 1

답변

2

으로 추가 할 것이다 것 작성자 : list comprehension :

df.columns = ['{}_{}'.format(col[0], col[1]) for col in df.columns] 
print (df) 
    Q007_A00_0 Q007_B00_0 Q007_C01_0 Q007_C01_1 Q007_C02_0 Q007_C02_1 Q007_C02_2 
0   Y   N   1   0  Text 1   0   0 
1   Y   N   4   0  Text 2   0   0 
2   Y   N   5   0  Text 3  Text 4  Text 5 
3   Y   N   2   0  Text 4   0   0 
4   Y   N   8   3  Text 5  Text 6   0 

그러나 열 이름에서 _0를 제거해야하는 경우 :

df.columns = ['{}{}'.format(col[0], '' if col[1] == 0 else '_' + str(col[1])) 
                     for col in df.columns] 
print (df) 
    Q007_A00 Q007_B00 Q007_C01 Q007_C01_1 Q007_C02 Q007_C02_1 Q007_C02_2 
0  Y  N  1   0 Text 1   0   0 
1  Y  N  4   0 Text 2   0   0 
2  Y  N  5   0 Text 3  Text 4  Text 5 
3  Y  N  2   0 Text 4   0   0 
4  Y  N  8   3 Text 5  Text 6   0 
관련 문제