私はpandas DataFrameを使用しています。使用する列の値はリストです。私は各リストの2つの要素を1つずつ結合し、別のDataFrameに出力したい。
たとえば、col_a
とcol_b
を含むデータフレームdf
があります。 col_b
の値はリストです。私はdf.col_b
の値をループし、ペアのリストを出力したい。pandasループ列の値
import pandas as pd
df=pd.DataFrame({'col_a':['ast1','ast2','ast3'],'col_b':[['text1','text2','text3'],['mext1','mext2','mext3'],['cext1','cext2']]})
df
col_a col_b
0 ast1 [text1, text2, text3]
1 ast2 [mext1, mext2, mext3]
2 ast3 [cext1, cext2]
私はこれ欲しい:
from itertools import combinations
(df.groupby('col_a')['col_b']
.apply(lambda x: pd.Series(list(combinations(x.iloc[0], 2))))
.reset_index(level = 0))
# col_a col_b
#0 ast1 (text1, text2)
#1 ast1 (text1, text3)
#2 ast1 (text2, text3)
#0 ast2 (mext1, mext2)
#1 ast2 (mext1, mext3)
#2 ast2 (mext2, mext3)
#0 ast3 (cext1, cext2)