pandas - 将值插入随机行
问题描述
我有一个如下的数据框。
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]})
我所看到的一切都是关于插入整个列而不是单个行。
解决方案
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
推荐阅读
- java - CData JDBC 驱动程序 | java.lang.Exception:找不到网络浏览器
- c++ - 将有状态 lambda 应用于整数序列值
- excel - MS Excel - VBA - 搜索 # 时出现问题,然后将相关单元格返回到不同的工作表
- c - 如何使用 uint8_t 数组 sprintf?
- sql - Kibana 中的 SQL 查询
- authentication - 是否可以将 HttpOnly Cookie 从一个域设置到另一个子域
- python - 如果日期是进行 DST(夏令时)更改的实际日期,有没有办法在 Python 中推断?
- swift - 如何在不同的类中调用 table.reloadData 之前为 Firebase 更新实现完成处理程序?
- javascript - NodeJS - 等到流式传输多个文件完成后再继续编写代码
- asp.net-core - 跨子域和 SecurityStampValidatorOptions 的 ASP.NET Core 3.1 身份 cookie