首页 > 解决方案 > 将行插入熊猫数据框中的随机位置

问题描述

我有一个非常大的示例数据框(约 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 

估算的行与数据框中的行具有相同的结构。

标签: pythonpython-3.xpandas

解决方案


如果以下是您输入的结构:

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

推荐阅读