python - 将行插入熊猫数据框中的随机位置
问题描述
我有一个非常大的示例数据框(约 640,000 行),我目前正在测试我构建的解析器是否可以检测到特定的短语。该数据框充满了文本字符串。
我试图找到一种方法将特定数量的行插入数据框中的随机位置。
这是数据框的基本结构:
Comments code
0 The stupidity of it is that gamed to total def... NaN
1 called poker face she s actually... WP
2 Example not identifying the fundamental scarci... NaN
3 No tol is bait That s the point... NaN
估算的行与数据框中的行具有相同的结构。
解决方案
如果以下是您输入的结构:
import pandas as pd
import numpy as np
df = pd.DataFrame({'Comments':['Text1','Text2','Text3','Text4'], 'code':['WP', np.nan, np.nan, np.nan]})
newrow = pd.DataFrame({"Comments":'Text_new', 'code':np.nan}, index=[0])
初始数据框:
Comments code
0 Text1 WP
1 Text2 NaN
2 Text3 NaN
3 Text4 NaN
要添加的新行:
Comments code
0 Text_new NaN
您可以使用这行代码将新行添加到数据框中的随机位置
from numpy.random import randint
random_row = randint(len(df)+1)
df = pd.concat([df.iloc[:random_row], newrow, df.iloc[random_row:]]).reset_index(drop=True)
输出:
Comments code
0 Text1 WP
1 Text2 NaN
2 Text3 NaN
3 Text_new NaN
4 Text4 NaN
推荐阅读
- reactjs - 您需要 Firebase 的 API 吗?
- google-chrome-extension - 传递给 chrome.downloads.download API 的文件名被忽略
- javascript - 如何在for循环中返回一个减一的数组中的一个值
- apache-spark - 加入 Spark 时不使用等于运算符
- azure - $ Azure 门户帐户创建的路径环境变量
- css - npm 说“未安装 webpack 安装 webpack 以开始捆绑”,即使我已经安装了 webpack
- flutter - 即使在多次请求之后,admob 中介 adcolony 仍然处于 0% 填充状态
- graphql - useQuery 错误对象为 graphQLErrors 属性返回空数组
- c# - Xamarin.Forms 标签中的超链接 - 索引超出范围
- python - 是否有相当于 tkinter 的 LabelFrame 的 Kivy?