2017-07-08 4 views
2

であるかどうかを確認する方法パンダ:リスト型のカラムは、私がリスト列から新しいリスト列を作成することができますどのようにデータフレーム

マイデータフレーム:

id x list_id 
1  20 [2, 4] 
2  10 [1, 3] 
3  10 [1] 
4  30 [1, 2] 

は、私が欲しいもの:

id x list_id list_x 
1  20 [2, 4]  [10, 30] 
2  10 [1, 3]  [20, 10] 
3  10 [1]  [20] 
4  30 [1, 2]  [20, 10] 

私の最初のアイデアは、idがリストに

for index, row in df.iterrows(): 
    if (df['id'].isin(row['list_id'])): 
    do_somthing 
あるかどうかを確認し、各ライン上に反復することです3210

しかし、その動作しない、任意の提案!

+0

とJECTアレイがどのようにそれを作成していますか?それはあなたが何をしたいのかによって異なります。 –

+0

'id'が 'list_id'に含まれているかどうかを確認しようとしていますが、どのアクションを実行するか明確ではありません。 –

+0

list_idカラムから新しいcoloumn list_xを作成する必要があります –

答えて

3

リスト内包使用:

df.loc[:,'list_x'] = [df.x[df['id'].isin(l)].values for l in df.list_id] 

ダミーデータとの完全な例:

import pandas as pd 

data= { 
    'id': [1,2,3,4], 
    'x': [20,10,10,30], 
    'list_id': [[2,4],[1,3],[1],[1,2]], 
} 

df = pd.DataFrame(data) 

df.loc[:,'list_x'] = [df.x[df['id'].isin(l)].values for l in df.list_id] 

出力

print df 

    list_id x list_x 
1 [2, 4] 20 [10, 30] 
2 [1, 3] 10 [20, 10] 
3  [1] 10  [20] 
4 [1, 2] 30 [20, 10] 
+0

スクリプトは完璧に動作します –

0

クリエイティブソリューション
numpy OBを使用しますset要素

i = np.array([set([x]) for x in df.id.values.tolist()]) 
x = np.empty(i.shape, dtype=object) 
x[:] = [[x] for x in df.x.values.tolist()] 
y = np.empty_like(x) 
y.fill([]) 
j = np.array([set(x) for x in df.list_id.values.tolist()]) 

df.assign(list_x=np.where(i <= j[:, None], x, y).sum(1)) 

    id x list_id list_x 
0 1 20 [2, 4] [10, 30] 
1 2 10 [1, 3] [20, 10] 
2 3 10  [1]  [20] 
3 4 30 [1, 2] [20, 10] 

タイミング

%timeit df.assign(list_x=[df.x[df['id'].isin(l)].values for l in df.list_id]) 

1000 loops, best of 3: 1.21 ms per loop 

%%timeit 
i = np.array([set([x]) for x in df.id.values.tolist()]) 
x = np.empty(i.shape, dtype=object) 
x[:] = [[x] for x in df.x.values.tolist()] 
y = np.empty_like(x) 
y.fill([]) 
j = np.array([set(x) for x in df.list_id.values.tolist()]) 

df.assign(list_x=np.where(i <= j[:, None], x, y).sum(1)) 

1000 loops, best of 3: 371 µs per loop 
関連する問題