【发布时间】:2019-06-03 19:28:05
【问题描述】:
我已经搜索了一些类似的问题,例如'Python中的等效R函数rep'。
在 R 中,rep 可用于数组或数据帧,您可以设置参数each 来指定是要重复每个元素还是重复整个列表/数据帧。
但在 Python 中,你必须区分数组和数据框。
对于数组,np.repeat 将重复每个元素,np.tile 将重复整个数组。
x=['a','b']
np.repeat(x,2)#repeat each element twice
Out[85]: array(['a', 'a', 'b', 'b'], dtype='<U1')
np.tile(x,2)#repeat the whole array twice
Out[86]: array(['a', 'b', 'a', 'b'], dtype='<U1')
对于 Pandas 数据框。 pd.concat 可用于重复整个数据帧:
d=pd.DataFrame({'x':['a','b'],'y':['c','d']})
d
Out[94]:
x y
0 a c
1 b d
pd.concat([d]*2)
Out[93]:
x y
0 a c
1 b d
0 a c
1 b d
我的问题是如何重复熊猫数据框中的每一行,而不是作为一个整体重复。我想要的结果是:
x y
a c
a c
b d
b d
无论如何,我希望 Python 中有一个类似'rep' 的函数,它可以用于 list 和 dataframe ,也可以指定整体重复或重复每个元素。
【问题讨论】:
标签: python r pandas dataframe rep