2016-07-20 4 views
0

とリストの2つの列をアンパック:私は、次のデータフレームを有する対応する要素

df = pd.DataFrame({'A' : [['on', 'ne', 'on'], ['tw'], 
         ['th', 'hr', 'ree'], []], 
        'B' : ['one', 'two', 'three','four'], 
        'C' : [0.2,0.6,-1.4,0.7], 
        'D' : [[0.2,0.3,-1.2],[0.5], 
         [0.9,0.1,0.0],[]]}) 

A及びDは、対応する値をリストの二つの列です。 私は単純に値をアンパックして、その値にします。

df = pd.DataFrame({'A' : ['on', 'ne', 'on', 'tw', 
         'th', 'hr', 'ree', N/A], 
        'B' : ['one', 'one','one','two', 
          'three', 'three','three','four'], 
        'C' : [0.2, 0.2, 0.2, 0.6, 
          -1.4, -1.4, -1.4, 0.7], 
        'D' : [0.2, 0.3, -1.2, 0.5, 
         0.9, 0.1, 0.0, N/A]}) 

私はアンスタックとピボットを試みましたが、成功しなかったので、何か助けになるでしょう。

+2

を?そのステップで問題を解決する方が適切かもしれません。 – root

+0

あなたの期待されるDFは存在できません。 ABCDの長さは等しくなければならない。 – Merlin

+1

'B'と 'C'の余分な値はどこから来ますか? – Alex

答えて

0

あなたはjoin使用することができますどのようにあなたが最初にデータフレームの中に、このデータを取得している

#DataFrame from Series, remove level 1 
df1 = pd.DataFrame({'A':df.A.apply(pd.Series).stack(), 
        'D':df.D.apply(pd.Series).stack()}).reset_index(drop=True, level=1) 
print (df1) 
    A D 
0 foo 0.2 
0 bar 0.3 
0 foo -1.2 
1 bar 0.5 
2 foo 0.9 
2 bar 0.1 
2 foo 0.0 

#join new df1 to subset df(columns B,C) and sort columns 
print (df[['B','C']].join(df1).sort_index(axis=1)) 
    A  B C D 
0 foo one 0.2 0.2 
0 bar one 0.2 0.3 
0 foo one 0.2 -1.2 
1 bar two 0.6 0.5 
2 foo three -1.4 0.9 
2 bar three -1.4 0.1 
2 foo three -1.4 0.0 
3 NaN two 0.7 NaN 
#reset index 
print (df[['B','C']].join(df1).sort_index(axis=1).reset_index(drop=True)) 
    A  B C D 
0 foo one 0.2 0.2 
1 bar one 0.2 0.3 
2 foo one 0.2 -1.2 
3 bar two 0.6 0.5 
4 foo three -1.4 0.9 
5 bar three -1.4 0.1 
6 foo three -1.4 0.0 
7 NaN two 0.7 NaN 
+0

これは私が欲しいものです!ありがとうございました。 – user2755526

+0

うれしいことができますよ!受け入れてくれてありがとう! – jezrael

関連する問題