【问题标题】:Comparing two sequence columns, and base on a condition add element to Dataframe比较两个序列列,并基于条件将元素添加到 Dataframe
【发布时间】:2021-07-19 20:56:44
【问题描述】:

你好,我正在寻找一个脚本可以帮助我解决以下问题的 Python:

有以下两列,我需要在序列之间创建间隙以使它们匹配

Input Output
Index column A column B column A column B
0 1 1 1 1
1 2 2 2 2
2 2 2 2 2
3 3 3 3 3
4 4 3 3
5 5 4 4 4
6 5 5 5 5
7 6 5 5 5
8 8 6 6 6
9 8 8 8 8
10 9 8 8 8
11 10 9 9 9
12 11 9 9
13 11 10 10 10
14 15 13 11
15 16 13 11
16 16 14 13
17 17 14 13
18 17 15 14
19 18 15 14
20 19 16 15 15
21 21 16 15
22 22 17 16 16
23 27 17 16 16
24 17 17
25 17 17
26 18
27 19
28 21
29 22
30 27

我试过了,但我的逻辑不起作用

我使用 Pandas 和 Python 尝试了不同的东西,首先我尝试将列转换为列表并逐个迭代它们但没有奏效,我最接近的方法是这个,但不幸的是仍然不起作用:

for i in df.index:
    if(df['column A'][i] != df['column B'][i]):
      df['column A'] = df['column A'][:i] + np.NaN + df['column A'][i:]
      #df['column A'][i] = df['column A'].append(pd.Series([np.NaN]))
      #df2['column A'] = df['column A'].loc[i] = np.NaN

我们将非常感谢您的所有帮助。 (感谢无限)

谢谢

【问题讨论】:

    标签: python pandas sequence series gaps-and-islands


    【解决方案1】:

    在迭代对象时更改对象通常是个坏主意。相反,只需将两个新列表初始化为空,并根据需要用原始列或 NaN 中的值填充它们。诀窍是分别迭代列 A 和 B 的索引,以便在另一个列表中填写 NaN 值时只能增加其中一个:

    a = df['column A'].values
    b = df['column B'].values
    
    a_out = []
    b_out = []
    
    i = 0
    j = 0
    
    while i < len(df) and j < len(df):
        if a[i] == b[j]:
            a_out.append(a[i])
            i += 1
            b_out.append(b[j])
            j += 1
        elif a[i] < b[j]:
            a_out.append(a[i])
            i += 1
            b_out.append(np.nan)
        else:
            a_out.append(np.nan)
            b_out.append(b[j])
            j += 1    
    
    if i < j:
        a_out.extend(a[i:])
        b_out.extend([np.nan] * len(a[i:]))
    elif i > j:
        b_out.extend(b[j:])
        a_out.extend([np.nan] * len(b[j:]))
            
    df_out = pd.DataFrame({'column A': a_out,
                           'column B': b_out}) 
    

    【讨论】:

    • 非常感谢,这段代码完美地符合我的逻辑✌我的问题是两个列表的迭代,但你是对的,让它们单独处理可以让事情正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多