首页 > 解决方案 > 循环熊猫数据框

问题描述

我有以下数据框并想做循环:

df = name
      a
      b
      c
      d

我试过下面的代码:

for index, row in df.iterrows():
    for line in df['name']:
        print(index, line)

但我想要的结果是如下的数据框:

df = name    name1
       a       a
       a       b
       a       c
       a       d
       b       a
       b       b
       b       c
       b       d
       etc.

有什么可能的方法吗?我知道这是一个愚蠢的问题,但我是 python 新手

标签: pythonpandas

解决方案


一种使用方式pandas.DataFrame.explode

df["name1"] = [df["name"] for _ in df["name"]]
df.explode("name1")

输出:

  name name1
0    a     a
0    a     b
0    a     c
0    a     d
1    b     a
1    b     b
1    b     c
1    b     d
2    c     a
2    c     b
2    c     c
2    c     d
3    d     a
3    d     b
3    d     c
3    d     d

推荐阅读