如何从两个具有日期时间索引的数据帧中复制值以填充一个数据帧?

问题描述 投票:0回答:1

我想定义一个函数如下...

我有两个数据框,在所有行中都有浮点值。 两个数据帧都以日期时间作为索引。 两个数据框都有不同的列。

我想获取最小的数据框并将这些列复制到最大的数据框中。 如果最小数据框在最大数据框之后开始,那么我想用最小数据框第一行中的第一个值填充最大数据框中的第一个日期。

如果最小数据框之前完成,那么我想用最小数据框最后一行中的最后一个值填充最大数据框中的最后一个日期。

结果必须是最大的数据框,其中包含最小 df 的列以及最后提到的详细信息

这就是我所做的,问题是我有空值。

def copy_up(df1, df2):
''' df1 and df2 must finish with the same date when you pass them as argument
df1, df2: Date time index, all float values in all columns
Returns the biggest data frame with all columns of the smallest df, fill the initial days repeating the first row of smallest df
'''

    #Checking columns are unique
    columnas_df1 = set(df1.columns)
    columnas_df2 = set(df2.columns)
    columnas_repetidas = columnas_df1.intersection(columnas_df2)


    if len(columnas_repetidas) > 0:
        print("¡Hay columnas repetidas en los DataFrames!")
        print("Columnas repetidas:", columnas_repetidas)
        return 0
    else:
        print("No hay columnas repetidas en los DataFrames.")
    # Compare which one is bigger

    if len(df1) > len(df2):
        df_grande = df1.copy()
        df_pequeno = df2.copy()
    else:
        df_grande = df2.copy()
        df_pequeno = df1.copy()

    #N of times we will repeat the first row is restante
    restante = len(df_grande) - len(df_pequeno)

    #Repeating first row in biggest data frame
    for i in df_pequeno.columns:
        lista_ultimos = list(df_pequeno[i].values)
        lista_primer = [lista_ultimos[0]] * restante
        final = lista_primer
        final.extend(lista_ultimos)
        df_grande[i] = final
    
    return df_grande

我用 copy_down(df1, df2) 函数做了类似的事情 然后我就这么做了

pd.concat([copy_down(df1, df2), copy_up(df1, df2)])

python pandas numpy concatenation autofill
1个回答
0
投票

假设这两个 DataFrame 与您引用的类似:

import pandas as pd

# Example DataFrame 1 (biggest)
df1 = pd.DataFrame(
    {
        "A": [1.1, 2.2, 3.3, 4.4, 5.5],
        "B": [6.6, 7.7, 8.8, 9.9, 10.0],
    },
    index=pd.date_range(start="2024-01-01", periods=5),
)

# Example DataFrame 2 (smallest)
df2 = pd.DataFrame(
    {
        "C": [11.1, 12.2, 13.3],
        "D": [14.4, 15.5, 16.6],
    },
    index=pd.date_range(start="2024-01-03", periods=3),
)
              A     B
2024-01-01  1.1   6.6
2024-01-02  2.2   7.7
2024-01-03  3.3   8.8
2024-01-04  4.4   9.9
2024-01-05  5.5  10.0
               C     D
2024-01-03  11.1  14.4
2024-01-04  12.2  15.5
2024-01-05  13.3  16.6

如果我理解你的逻辑,你可以进行外部合并,然后回填和前向填充空值:

df = pd.merge(df1, df2, how="outer", left_index=True, right_index=True).bfill().ffill()

对于示例,结果将是:

              A     B     C     D
2024-01-01  1.1   6.6  11.1  14.4
2024-01-02  2.2   7.7  11.1  14.4
2024-01-03  3.3   8.8  11.1  14.4
2024-01-04  4.4   9.9  12.2  15.5
2024-01-05  5.5  10.0  13.3  16.6
© www.soinside.com 2019 - 2024. All rights reserved.