我有这个 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/