【问题标题】:Equivalent 'rep' of R in Pandas dataframePandas 数据框中 R 的等效“代表”
【发布时间】: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


    【解决方案1】:

    pandas 中,您可以将reindexnp.repeat 一起使用

    d.reindex(np.repeat(df.index.values,2))
       x  y
    0  a  c
    0  a  c
    1  b  d
    1  b  d
    

    或者重新构建你的数据框

    pd.DataFrame(np.repeat(d.values,2,axis=0),columns=d.columns)
       x  y
    0  a  c
    1  a  c
    2  b  d
    3  b  d
    

    还有concatsort_index

    pd.concat([d]*2).sort_index()
       x  y
    0  a  c
    0  a  c
    1  b  d
    1  b  d
    

    【讨论】:

    • d.reindex(np.repeat(df.index.values,2)) 这个更快。 +1 :)
    【解决方案2】:

    您也可以将np.repeatnp.arange 一起使用:

    In [183]: d.iloc[np.repeat(np.arange(len(d)), 2)]
    Out[183]: 
       x  y
    0  a  c
    0  a  c
    1  b  d
    1  b  d
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 2021-03-05
      • 2017-05-23
      • 2023-01-31
      • 2019-01-14
      • 2017-12-13
      • 2014-05-31
      相关资源
      最近更新 更多