3 回答
TA贡献1829条经验 获得超13个赞
IIUC 使用 product
import itertools
yourdf=pd.DataFrame(list(itertools.product(*df.values.T.tolist())),columns=df.columns)
yourdf
Out[937]:
Name Surname MiddleName
0 James Bond A
1 James Bond B
2 James Sweenie A
3 James Sweenie B
4 Maggie Bond A
5 Maggie Bond B
6 Maggie Sweenie A
7 Maggie Sweenie B
TA贡献1845条经验 获得超8个赞
您正在寻找一种expand_grid可以使用itertools.product(). 从pandas 文档中,您可以定义expand_grid:
import itertools
def expand_grid(data_dict):
rows = itertools.product(*data_dict.values())
return pd.DataFrame.from_records(rows, columns=data_dict.keys())
expand_grid(df.to_dict('list'))
Out[38]:
Name Surname MidName
0 James Bond A
1 James Bond B
2 James Sweenie A
3 James Sweenie B
4 Maggie Bond A
5 Maggie Bond B
6 Maggie Sweenie A
7 Maggie Sweenie B
TA贡献1841条经验 获得超3个赞
没有迭代工具:
pd.MultiIndex.from_product(df.T.values.tolist()).to_frame(index=False)
添加回答
举报