【问题标题】:How to repeat pandas dataframe records based on column value如何根据列值重复熊猫数据框记录
【发布时间】:2019-05-14 02:13:37
【问题描述】:

我正在尝试根据其中一列中的 int 值复制 pandas DataFrame(v.0.23.4,python v.3.7.1)的行。我正在应用来自this question 的代码来执行此操作,但我遇到了以下数据类型转换错误:TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'。基本上,我不明白为什么这段代码试图转换为int32。

从这里开始,

dummy_dict = {'c1': ['a','b','c'],
              'c2': [0,1,2]}
dummy_df = pd.DataFrame(dummy_dict)
    c1  c2  c3
0   a   0   textA
1   b   1   textB
2   c   2   textC

我正在这样做

dummy_df_test = dummy_df.reindex(dummy_df.index.repeat(dummy_df['c2']))

最后我想要这个。但是,我收到了上述错误。

    c1  c2  c3
0   a   0   textA
1   b   1   textB
2   c   2   textC
3   c   2   textC

【问题讨论】:

  • 试试:dummy_df_test = dummy_df.reindex(dummy_df.index.repeat(dummy_df['c2'].astype("int32")))
  • 注意,您应该将0 替换为1,否则它将被repeat 删除。但对我来说,这适用于pandas 0.24.2: df.reindex(df.index.repeat(df.replace(0, 1).c2))`
  • 谢谢,@PMende 和 erfan,这些都是有用的答案。

标签: python pandas


【解决方案1】:

只是一种解决方法:

pd.concat([dummy_df[dummy_df.c2.eq(0)],dummy_df.loc[dummy_df.index.repeat(dummy_df.c2)]])

@Wen 提供的另一个绝妙建议

dummy_df.reindex(dummy_df.index.repeat(dummy_df['c2'].clip(lower=1)))

  c1  c2
0  a   0
1  b   1
2  c   2
2  c   2

【讨论】:

  • 嗯,dummy_df.reindex(dummy_df.index.repeat(dummy_df['c2'].clip(lower=1))) 怎么样
  • @WeNYoBen 太棒了,如果您愿意,可以将其发布为答案。 :)
  • 不用担心,请随意加入您的 :-)
【解决方案2】:

我相信可以在此处找到有关其发生原因的答案: https://github.com/numpy/numpy/issues/4384

将 dtype 指定为 int32 应该可以解决原始注释中突出显示的问题。

【讨论】:

    【解决方案3】:

    第一次尝试复制所有行,第二次尝试复制索引为 2 的行。感谢concat 函数。

    df2 = pd.concat([df]*2, ignore_index=True)
    print(df2)
    
    df3= pd.concat([df, df.iloc[[2]]])
    print(df3)
    

      c1  c2     c3
    0  a   0  textA
    1  b   1  textB
    2  c   2  textC
      c1  c2     c3
    0  a   0  textA
    1  b   1  textB
    2  c   2  textC
    3  a   0  textA
    4  b   1  textB
    5  c   2  textC
      c1  c2     c3
    0  a   0  textA
    1  b   1  textB
    2  c   2  textC
    2  c   2  textC
    

    如果你打算在最后重置索引

    df3=df3.reset_index(drop=True)
    

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 2021-12-20
      • 2019-03-20
      • 2021-12-30
      • 2021-05-04
      • 2017-11-30
      • 1970-01-01
      • 2021-10-28
      • 2021-09-17
      相关资源
      最近更新 更多