2017-12-05 7 views
0

私はパンダのデータフレームのように持ってDATAFRAME:スプリット1つの列が

df = pd.DataFrame(['A',1,2,3,'B',4,5,'C',6,7,8,9])

0 
0 A 
1 1 
2 2 
3 3 
4 B 
5 4 
6 5 
7 C 
8 6 
9 7 
10 8 
11 9 

それは、文字列と数字の組み合わせです。私はこのDFを以下のようなトウの列に分割したいと考えています:

name value 
0 A 1 
1 A 2 
2 A 3 
3 B 4 
4 B 5 
5 C 6 
6 C 7 
7 C 8 
8 C 9 

これを行うにはどのような方法が適していますか?

答えて

1

df = pd.DataFrame({0 :['A',1,2,3,'B',4,5,'C',6,7,8,9]}) 
#check strings 
mask = df[0].astype(str).str.isalpha() 
#check if mixed values - numeric with strings 
#mask = df[0].apply(lambda x: isinstance(x, str)) 
#create column to first position, create NaNs filled by forward filling 
df.insert(0, 'name', df[0].where(mask).ffill()) 
#remove rows with same values - with names, rename column 
df = df[df['name'] != df[0]].rename(columns={0:'value'}).reset_index(drop=True) 
print (df) 
    name value 
0 A  1 
1 A  2 
2 A  3 
3 B  4 
4 B  5 
5 C  6 
6 C  7 
7 C  8 
8 C  9 

または:

out = [] 
acc = None 
for x in df[0]: 
    #check if strings 
    if isinstance(x, str): 
     #assign to variable for tuples 
     acc = x 
    else: 
     #append tuple to out 
     out.append((acc, x)) 
print (out) 

df = pd.DataFrame(out, columns=['name','value']) 
print (df) 
    name value 
0 A  1 
1 A  2 
2 A  3 
3 B  4 
4 B  5 
5 C  6 
6 C  7 
7 C  8 
8 C  9 
0

これは、あなたが望む結果を得るためにあなたのデータ構造を与える:

input = ['A',1,2,3,'B',4,5,'C',6,7,8,9] 
letter = None 
output = [] 
for i in input: 
    if type(i) is type(''): 
     letter = i 
    elif type(i) is type(0) and letter is not None: 
     output.append((letter, i)) 
print(output) 

出力は今、あなたが望むようにペアリング、タプルの配列を有します。私はパンダを使用していませんが、これがあなたに役立つことを願っています。

0

IIUC

df['New']=df[df.your.str.isalpha().fillna(False)] 
df.ffill().loc[df.your!=df.New,:] 
Out[217]: 
    your New 
1  1 A 
2  2 A 
3  3 A 
5  4 B 
6  5 B 
8  6 C 
9  7 C 
10 8 C 
11 9 C 

データ入力を使用でき

df = pd.DataFrame({'your':['A',1,2,3,'B',4,5,'C',6,7,8,9]})