Pandas 如果一个列值在一个数据帧中没有一定数量的出现,如何用该列值复制所有行?
这是我的数据帧Pandas 如果一个列值在一个数据帧中没有一定数量的出现,如何用该列值复制所有行?,pandas,Pandas,这是我的数据帧 A B 0 a 5 1 b 2 2 d 5 3 g 3 4 m 2 5 c 0 6 u 5 7 p 3 8 q 1 9 z 1 如果列B中某个特定值的数量没有特定的出现次数,我想复制所有具有该特定值的行 对于上述df,假设该特定值为3。如果列B的值小于3,则具有该列值的所有行都将被复制。因此,列值为0、1和2的行是重复的,但列b值为5的行不是 预期结果: A B 0 a
A B
0 a 5
1 b 2
2 d 5
3 g 3
4 m 2
5 c 0
6 u 5
7 p 3
8 q 1
9 z 1
如果列B中某个特定值的数量没有特定的出现次数,我想复制所有具有该特定值的行
对于上述df,假设该特定值为3。如果列B的值小于3,则具有该列值的所有行都将被复制。因此,列值为0、1和2的行是重复的,但列b值为5的行不是
预期结果:
A B
0 a 5
1 b 2
2 d 5
3 g 3
4 m 2
5 c 0
6 u 5
7 p 3
8 q 1
9 z 1
10 b 2
11 m 2
12 g 3
13 p 3
14 c 0
15 c 0
这是我的方法
输出
如果我们不想复制,而是想乘以一个因子d,
我们必须作出以下修改:
n = 3
d = 2
m_ffill = notNaN_count.mul(d).lt(n)
repeats = notNaN_count.lt(n).mul(~m_ffill).mul(d).clip(lower = 1)
编辑
那么,重要的是价值或价值本身的出现次数?我正在为机器学习模型创建训练数据。数据集不平衡;一个类有很多数据点,但另一个类的数据点很少,因此我需要为样本数很少的数据点增加数据。如果其他值有多个列,我们将如何更改它。就像A列和其他东西一样,当我尝试我的数据时,我得到ValueError:函数不会减少。我一直在想到底出了什么问题。dfshuff.assigncolumns=dfshuff.groupby'Cat_ID'。cumcount似乎工作正常。因此,问题发生在pivot表的某个地方:.pivot_tablecolumns='columns'。
A B
0 c 0
1 c 0
2 c 0
3 q 1
4 z 1
5 q 1
6 z 1
7 b 2
8 m 2
9 b 2
10 m 2
11 g 3
12 p 3
13 g 3
14 p 3
15 a 5
16 d 5
17 u 5
n = 3
d = 2
m_ffill = notNaN_count.mul(d).lt(n)
repeats = notNaN_count.lt(n).mul(~m_ffill).mul(d).clip(lower = 1)
n=3 #threshold
d = 2
values = df.columns.difference(['B'])
df2 = (df.assign(columns = df.groupby('B').cumcount())
.pivot_table(columns = 'columns',
index = 'B',
values = values,
aggfunc = 'first'))
r = max(n,len(df2.columns.get_level_values('columns').unique()))
df2 = df2.reindex(columns = range(r),level = 'columns')
notNaN_count = df2.count(axis=1).div(len(values))
m_ffill = notNaN_count.mul(d).lt(n)
repeats = notNaN_count.lt(n).mul(~m_ffill).mul(d).clip(lower = 1)
new_df = (df2.T
.groupby(level=0)
.ffill()
.T
.where(m_ffill,df2)
.reindex(index = df2.index.repeat(repeats))
.stack()
.reset_index()
.loc[:,df.columns]
)