如何将Dataframe单元格内的列表分解为不同的行我想把包含一个列表的熊猫单元格变成每个值的行。所以,拿着这个:如果我想在nearest_neighbors列,以便每个值都是每个值中的一行。opponent索引,我该怎么做呢?有熊猫的方法是为了这样的操作吗?
3 回答
慕雪6442864
TA贡献1812条经验 获得超5个赞
lambda
nearest_neighbors
name
opponent
.
name
opponent
).
df = (pd.DataFrame({'name': ['A.J. Price'] * 3, 'opponent': ['76ers', 'blazers', 'bobcats'], 'nearest_neighbors': [['Zach LaVine', 'Jeremy Lin', 'Nate Robinson', 'Isaia']] * 3}) .set_index(['name', 'opponent']))>>> df nearest_neighbors name opponent A.J. Price 76ers [Zach LaVine, Jeremy Lin, Nate Robinson, Isaia] blazers [Zach LaVine, Jeremy Lin, Nate Robinson, Isaia] bobcats [Zach LaVine, Jeremy Lin, Nate Robinson, Isaia]df.reset_index(inplace=True)rows = []_ = df.apply(lambda row: [rows.append([row['name'], row['opponent'], nn]) for nn in row.nearest_neighbors], axis=1)df_new = pd.DataFrame(rows, columns=df.columns).set_index(['name', 'opponent'])>>> df_new nearest_neighbors name opponent A.J. Price 76ers Zach LaVine 76ers Jeremy Lin 76ers Nate Robinson 76ers Isaia blazers Zach LaVine blazers Jeremy Lin blazers Nate Robinson blazers Isaia bobcats Zach LaVine bobcats Jeremy Lin bobcats Nate Robinson bobcats Isaia
>>> (pd.melt(df.nearest_neighbors.apply(pd.Series).reset_index(), id_vars=['name', 'opponent'], value_name='nearest_neighbors') .set_index(['name', 'opponent']) .drop('variable', axis=1) .dropna() .sort_index() )
添加回答
举报
0/150
提交
取消