python - Pandas - 根据列值创建重复行,给定该列的阈值

标签 python pandas dataframe

我有这个 pandas 数据框:

A    B     C
20   6     7 
5    3.8   9
34   4     1

如果 A 中的值大于 10,我想创建重复行。 所以数据框最终应该看起来像:

A    B     C
10   6     7
10   6     7
5    3.8   9
10   4     1
10   4     1
10   4     1
4    4     1

pandas 有没有办法优雅地做到这一点?或者我将不得不遍历行并手动执行......? 我已经在 StackOverflow 上浏览过类似的查询,但没有一个完全符合我的要求。

最佳答案

用途:

#create default index
df = df.reset_index(drop=True)

#get floor and modulo divisions
a = df['A'] // 10 
b = (df['A'] % 10)

#repeat once if not 0
df2 = df.loc[df.index.repeat(b.ne(0).astype(int))]
#repplace values of A with map by index 
df2['A'] = df2.index.map(b.get)

#repeat with assign scalar 10
df1 = df.loc[df.index.repeat(a)].assign(A=10)

#join together, sort index and create default RangeIndex
df = df1.append(df2).sort_index().reset_index(drop=True)
print (df)
    A    B  C
0  10  6.0  7
1  10  6.0  7
2   5  3.8  9
3  10  4.0  1
4  10  4.0  1
5  10  4.0  1
6   4  4.0  1

关于python - Pandas - 根据列值创建重复行,给定该列的阈值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50797556/

相关文章:

Python:读取和写入二进制数据

python - 你会如何解析缩进(python 风格)?

Python 请求发送前查看

python - pandas 在列的子集上应用自定义函数

python - 计算给定速度的加速度

python - 关闭 Ubuntu 的脚本

python - 将数据帧附加到 sqlite3 表,BLOB 而不是时间戳

python - 如何拆分数据框并将其存储在 Excel 文件的多个工作表中

python - 无法将简单的文本文件转换为 pandas 数据框

python - 错误: 'str' object has no attribute 'shape' while trying to covert datetime in a dataframe