如何在pandas DataFrame中复制行并添加id列

时间:2014-04-28 02:49:29

标签: python pandas

我有一个数据框,例如:

from pandas import DataFrame
import pandas as pd
x = DataFrame.from_dict({'farm' : ['A','B','A','B'], 
                         'fruit':['apple','apple','pear','pear']})

如何使用id复制N次,例如。输出(N=2):

  farm  fruit  sim
0    A  apple    0
1    B  apple    0
2    A   pear    0
3    B   pear    0
0    A  apple    1
1    B  apple    1
2    A   pear    1
3    B   pear    1

我尝试了一种适用于R:

中的数据帧的方法
from numpy import arange
N = 2
sim_ids = DataFrame(arange(N))
pd.merge(left=x, right=sim_ids, how='left')

但失败并显示错误MergeError: No common columns to perform merge on

感谢。

2 个答案:

答案 0 :(得分:1)

不确定R在那里做什么,但这是一种做你想做的事情的方法:

In [150]: x
Out[150]:
  farm  fruit
0    A  apple
1    B  apple
2    A   pear
3    B   pear

[4 rows x 2 columns]

In [151]: N = 2

In [152]: DataFrame(tile(x, (N, 1)), columns=x.columns).join(DataFrame({'sims': repeat(arange(N), len(x))}))
Out[152]:
  farm  fruit  sims
0    A  apple     0
1    B  apple     0
2    A   pear     0
3    B   pear     0
4    A  apple     1
5    B  apple     1
6    A   pear     1
7    B   pear     1

[8 rows x 3 columns]

In [153]: N = 3

In [154]: DataFrame(tile(x, (N, 1)), columns=x.columns).join(DataFrame({'sims': repeat(arange(N), len(x))}))
Out[154]:
   farm  fruit  sims
0     A  apple     0
1     B  apple     0
2     A   pear     0
3     B   pear     0
4     A  apple     1
5     B  apple     1
6     A   pear     1
7     B   pear     1
8     A  apple     2
9     B  apple     2
10    A   pear     2
11    B   pear     2

[12 rows x 3 columns]

答案 1 :(得分:1)

我可能会这样做:

>>> df_new = pd.concat([df]*2)
>>> df_new["id"] = df_new.groupby(level=0).cumcount()
>>> df_new
  farm  fruit  id
0    A  apple   0
1    B  apple   0
2    A   pear   0
3    B   pear   0
0    A  apple   1
1    B  apple   1
2    A   pear   1
3    B   pear   1

[8 rows x 3 columns]