我有一个数据帧,希望根据列中的值复制特定行,并寻找一种简单的方法.

import pandas as pd

data= [['Karan',23],['Rohit',22],['Macron',22], ['Sahil',21],['Aryan',24]]

df = pd.DataFrame(data, columns=['Name','Age'])

因此,我的最终数据帧应该看起来像[行顺序不重要]

Name Age
Karan 23
Rohit 22
Rohit 22
Macron 22
Macron 22
Sahil 21
Aryan 24
Aryan 24

已try [https://stackoverflow.com/questions/24029659/python-pandas-replicate-rows-in-dataframe]但不能处理带有字符串的数据.

推荐答案

您可以使用Index.repeat:

df.loc[df.index.repeat(df['Age'].isin([22,24]).add(1))]

工作原理:

  • 确定年龄是否在[22,24]
  • 加1(False个值变为1True变为2)
  • 重复索引并重新索引

或者,为了获得更大的灵活性,使用numpy.where,您可以 Select 任何想要的值:

import numpy as np
df.loc[df.index.repeat(np.where(df['Age'].isin([22,24]), 2, 1))]

输出:

     Name  Age
0   Karan   23
1   Rohit   22
1   Rohit   22
2  Macron   22
2  Macron   22
3   Sahil   21
4   Aryan   24
4   Aryan   24
resetting the index:
df.loc[df.index.repeat(df['Age'].isin([22,24]).add(1))].reset_index(drop=True)

输出:

     Name  Age
0   Karan   23
1   Rohit   22
2   Rohit   22
3  Macron   22
4  Macron   22
5   Sahil   21
6   Aryan   24
7   Aryan   24

Python相关问答推荐

Pandas 第二小值有条件

如何将ctyles.POINTER(ctyles.c_float)转换为int?

Python+线程\TrocessPoolExecutor

什么是最好的方法来切割一个相框到一个面具的第一个实例?

CommandeError:模块numba没有属性generated_jit''''

在Python 3中,如何让客户端打开一个套接字到服务器,发送一行JSON编码的数据,读回一行JSON编码的数据,然后继续?

如何在PySide/Qt QColumbnView中删除列

网格基于1.Y轴与2.x轴显示在matplotlib中

matplotlib图中的复杂箭头形状

使用Openpyxl从Excel中的折线图更改图表样式

当单元测试失败时,是否有一个惯例会抛出许多类似的错误消息?

如何强制向量中的特定元素在Gekko中处于优化解决方案中

Django.core.exceptions.SynchronousOnlyOperation您不能从异步上下文中调用它-请使用线程或SYNC_TO_ASYNC

对于标准的原始类型注释,从键入`和`从www.example.com `?

我怎样才能让深度测试在OpenGL中使用Python和PyGame呢?

如何在表单中添加管理员风格的输入(PDF)

Fake pathlib.使用pyfakefs的类变量中的路径'

401使用有效的OAuth令牌向Google Apps脚本Web App发出POST请求时出现未经授权的错误(";

Pandas:新列,从列表中采样,基于列值

为什么fizzbuzz在两个数字的条件出现在一个数字的条件之后时不起作用?