通过在具有非数值的两行上应用插值函数从旧数据框创建新数据框

create new dataframe from old one by applying an interpolation function on two rows with non-numeric values

我的数据框缺少一些行。我想 select 2 行(selection 是单独完成的)并在这两行之间插入值。如果我在这两行中生成 x 行,我想将两个结束行的值重复到中点。列是非数字值,我基本上复制其中一行的列的值。 例如,如果我有以下行: 我的旧值数据框是:

df_old : 
   fname    lname     occupation
0   Alex    Schapiro    teacher
1   paul    Gorman       nurse

我写了一个函数,它接受一个名为 data_col 的列(具有 2 个值)和一个新点列表来为它们生成值(称为 new_x)。它找到列表中的中点 (new_x) 并将列的第一个值重复到中点,并从中点到列表长度的末尾重复列的第二个值。结果将是生成的值列表。

def generate_object_dtype(data_col,new_x):
    new_val = []
    mid_tp = middle(new_x)
    new_val.extend([data_col.iloc[0]]*sum(i <= mid_tp for i in new_x))
    new_val.extend([data_col.iloc[1]]*sum(i > mid_tp for i in new_x))

    return(new_val)



function to find mid point of the list :
def middle(a):
    a = sorted(a)
    l = len(a)

    if len(a) % 2 == 0.:
        m = (a[int(l / 2)] + a[int(l / 2) - 1]) / 2.
    else:
        if l < 2:
            m = a[0]
        else:
            m = a[int(l / 2)]

    return m

现在,我在我的 old_df 上应用生成函数来创建一个新的 df,其中包含非数字列值的插值行:

    >>old_data.apply(lambda col: generate_object_dtype(col, new_x), axis=0) 

fname                     [Alex, Alex, paul, paul]
lname         [Schapiro, Schapiro, Gorman, Gorman]
occupation        [teacher, teacher, nurse, nurse]
dtype: object

结果是一系列列表。我需要结果是这样的数据框: new_df :

   fname    lname     occupation
0   Alex    Schapiro    teacher
1   Alex    Schapiro    teacher
2   paul    Gorman       nurse
3   paul    Gorman       nurse

我该怎么做? ps。一般来说,将函数应用于数据框是否正确,结果是具有全新值的新数据框: 即

new_df = old_df.apply(lambda col: generate_object_dtype(col, new_x), axis=0) 

谢谢!

让我们看看你的声明,你可以只提供一个 number of rows

import numpy as np

nrows = 4
new_x = np.arange(0, nrows, 1)

# Make sure the index begins at 0, in case you slice from another part of the `df`
df = df.reset_index(drop=True)

# Move the second value to the midpoint
df.index = df.index*nrows//2

# Fill the missing values forward
df = df.reindex(new_x).ffill()

输出:

  fname     lname occupation
0  Alex  Schapiro    teacher
1  Alex  Schapiro    teacher
2  paul    Gorman      nurse
3  paul    Gorman      nurse

如果您有奇数行,这将重复后一行 1 次。随着 nrows=5

  fname     lname occupation
0  Alex  Schapiro    teacher
1  Alex  Schapiro    teacher
2  paul    Gorman      nurse
3  paul    Gorman      nurse
4  paul    Gorman      nurse

您可以将索引修改为:

if nrows%2:
    df.index = df.index*(nrows//2+1)
else:
    df.index = df.index*nrows//2

然后将输出:

  fname     lname occupation
0  Alex  Schapiro    teacher
1  Alex  Schapiro    teacher
2  Alex  Schapiro    teacher
3  paul    Gorman      nurse
4  paul    Gorman      nurse