遍历大熊猫中的行并添加到迭代中

时间:2018-09-21 14:38:09

标签: python pandas

考虑以下数据框

df = pd.DataFrame({'ID' : [1,2,3,4,5], 'Week' : ['WK1', 'WK2', 'WK3', 'WK4', 'WK5']})
print(df)
        ID  Week
0   1   WK1
1   2   WK2
2   3   WK3
3   4   WK4
4   5   WK5

循环和复制每一行同时将周数加+1的最Pythonic方式是

因此基于前两个值,这将是我想要的结果。

   ID   Week
0   1   WK1
1   1   WK2
2   1   WK3
3   1   WK4
4   1   WK5
5   2   WK1
6   2   WK2
7   2   WK3
8   2   WK4
9   2   WK5

2 个答案:

答案 0 :(得分:2)

这是笛卡尔积。理解并重建您的DataFrame

pd.DataFrame([(i, w) for i in df.ID for w in df.Week], columns=df.columns)

    ID Week
0    1  WK1
1    1  WK2
2    1  WK3
3    1  WK4
4    1  WK5
5    2  WK1
6    2  WK2
7    2  WK3
8    2  WK4
9    2  WK5
10   3  WK1
11   3  WK2
12   3  WK3
13   3  WK4
14   3  WK5
15   4  WK1
16   4  WK2
17   4  WK3
18   4  WK4
19   4  WK5
20   5  WK1
21   5  WK2
22   5  WK3
23   5  WK4
24   5  WK5

相同
# empty list
a = []

for i in df.ID:
    for w in df.Week:
        a.append((i, w))

pd.DataFrame(a, columns=df.columns)

答案 1 :(得分:2)

unstackbfillffill一起使用

df.set_index('ID',append=True).Week.unstack().ffill(1).bfill(1).stack().sort_index(level=1).reset_index(level=1)
Out[1025]: 
   ID    0
0   1  WK1
1   1  WK2
2   1  WK3
3   1  WK4
4   1  WK5
0   2  WK1
1   2  WK2
2   2  WK3
3   2  WK4
4   2  WK5
0   3  WK1
1   3  WK2
2   3  WK3
3   3  WK4
4   3  WK5
0   4  WK1
1   4  WK2
2   4  WK3
3   4  WK4
4   4  WK5
0   5  WK1
1   5  WK2
2   5  WK3
3   5  WK4
4   5  WK5