首页 > 解决方案 > 将值插入随机行

问题描述

我有一个如下的数据框。

D1 = pd.DataFrame({'a': [15, 22, 107, 120],
                   'b': [25, 21, 95, 110]})

我正在尝试在“b”列中随机添加两行以获得下面的效果。在每种情况下,在这种情况下插入的 0 都会将行向下移动一个。

D1 = pd.DataFrame({'a': [15, 22, 107, 120, 0, 0],
                   'b': [0, 25, 21, 0, 95, 110]})

我所看到的一切都是关于插入整个列而不是单个行。

标签: pandasrandom

解决方案


numpy.random.randint这是使用and实现此目的的一种潜在方法numpy.insert

import numpy as np

n = 2
rand_idx = np.random.randint(0, len(D1), size=n)

# Append 'n' rows of zeroes to D1
D2 = D1.append(pd.DataFrame(np.zeros((n, D1.shape[1])), columns=D1.columns, dtype=int), ignore_index=True)

# Insert n zeroes into random indices and assign back to column 'b'
D2['b'] = np.insert(D1['b'].values, rand_idx, 0)
print(D2)

     a    b
0   15   25
1   22    0
2  107    0
3  120   21
4    0   95
5    0  110

推荐阅读