【问题标题】:Using a list of values to specify the index location at which to insert a new row使用值列表指定插入新行的索引位置
【发布时间】:2018-03-08 22:23:02
【问题描述】:

我有一个数据框(220 行 × 2 列)和一个值列表 [41、84、129、174、219、45]。我想在我的列表中指定的索引位置下方的数据框中插入新行(包含 -999、-999)。举个例子。

40   400  -47.595322  
41   410   13.159509  
42     0 -235.865433  
43     8 -102.183365 

会变成:

40   400  -47.595322  
41   410   13.159509  
42   -999  -999  
43     0 -235.865433  
44     8 -102.183365  

等等等等……
谢谢:)

到目前为止我所拥有的:

import pandas as pd
import numpy as np
import glob
path =r'MyPath'
allFiles = glob.glob(path + "/*.dat")

frame = pd.DataFrame()
list_ = []
for file_ in allFiles:
    df = pd.read_csv(file_, delim_whitespace=True, index_col=None, header=None)
    list_.append(df)

frame = pd.concat(list_)
frame.columns = ['age', 'dt']
frame = frame.reset_index(drop=True)
idx = [] + list(frame['age'][frame['age'] == 410].index) + [df.index[-1]+1]
idx = np.array(idx)

df = pd.DataFrame(
np.insert(frame.values, idx + 1, -999, axis=0), columns=frame.columns)


print(df.to_string())

【问题讨论】:

    标签: list pandas dataframe insert row


    【解决方案1】:

    如果您的数据框包含单调递增的索引,您可以使用 np.insert 非常简单地做到这一点:

    idx = np.array([41, 84, 129, 174, 219, 45])
    df = pd.DataFrame(
        np.insert(df.values, idx + 1, -999, axis=0), columns=df.columns
    )
    

    如果没有,您需要调用 index.get_loc 来获取数组中的正确索引:

    idx = [df.index.get_loc(i) + 1 for i in idx]
    

    并像以前一样调用插入代码。


    演示:

    df
        A    B           C
    0  40  400  -47.595322
    1  41  410   13.159509
    2  42    0 -235.865433
    3  43    8 -102.183365
    
    idx = np.array([1, 3])
    pd.DataFrame(
        np.insert(df.values, idx + 1, -999, axis=0), columns=df.columns
    )
    
           A      B           C
    0   40.0  400.0  -47.595322
    1   41.0  410.0   13.159509
    2 -999.0 -999.0 -999.000000
    3   42.0    0.0 -235.865433
    4   43.0    8.0 -102.183365
    5 -999.0 -999.0 -999.000000
    

    注意无效的索引访问。

    【讨论】:

    • 在很大程度上感谢您的帮助,您的代码运行良好,但出于某种奇怪的原因,即使该值不在列表中,也会在索引 48 处添加一行。对此有什么想法吗?
    • @user9454050 你能再检查一下吗?那不应该发生:)
    • 我重新启动了我的笔记本并再次运行它。仍在附加到索引 48...
    • @user9454050 你能在你的问题中创建一个minimal reproducible example 吗?我试试看能不能调试
    • @user9454050 您的代码是一回事,但我需要可以重现此问题的数据。是否可以?至少有几行,只要足以告诉我这行不通……它对我有用。
    猜你喜欢
    • 2021-03-25
    • 2015-10-09
    • 2023-04-08
    • 2021-12-27
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    相关资源
    最近更新 更多