【问题标题】:Repeat Rows in Data Frame n Times [duplicate]在数据框中重复行 n 次 [重复]
【发布时间】:2018-08-10 22:58:35
【问题描述】:

考虑这样定义的数据框:

import pandas as pd
test = pd.DataFrame({
    'id' : ['a', 'b', 'c', 'd'],
    'times' : [2, 3, 1, 5]
})

是否可以从中创建一个新的数据框,其中每一行重复times 次,结果如下所示:

>>> result
   id  times
0   a      2
1   a      2
2   b      3
3   b      3
4   b      3
5   c      1
6   d      5
7   d      5
8   d      5
9   d      5
10  d      5

【问题讨论】:

  • 这很公平。我想我的问题是:这可能吗?目前正在摸索test.indextest.iloc[x] 尝试。
  • 有帮助。谢谢。
  • @MrT 当场,那是骗子

标签: python pandas


【解决方案1】:

使用pd.DataFrame.locpd.Index.repeat 的组合

test.loc[test.index.repeat(test.times)]

  id  times
0  a      2
0  a      2
1  b      3
1  b      3
1  b      3
2  c      1
3  d      5
3  d      5
3  d      5
3  d      5
3  d      5

要模仿您的确切输出,请使用reset_index

test.loc[test.index.repeat(test.times)].reset_index(drop=True)

   id  times
0   a      2
1   a      2
2   b      3
3   b      3
4   b      3
5   c      1
6   d      5
7   d      5
8   d      5
9   d      5
10  d      5

【讨论】:

    猜你喜欢
    • 2019-05-09
    • 2013-08-14
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多