如何在pandas df列中删除和移位值

7 python merge del pandas

我有一个pandas df我想要操纵的,所以它是有序的.所以对于df下面,我想['I']订购.因此,数值将为10-50.我有2个选项可以做到这一点;

1)尝试删除Column ['G']或中的值['H'].因此,如果值被== X删除.

2)尝试合并相同列中的值 == X

import pandas as pd

d = pd.DataFrame({
        'J' : [10,'B','C','C',50],
        'I' : ['B',20,30,40,'C'],
        'H' : ['X','A','C','B','X'],         
        'G' : ['X', 'B', 'A','B','X'],                                 
        })
Run Code Online (Sandbox Code Playgroud)

输出:

   G  H   I   J
0  X  X   B  10
1  B  A  20   B
2  A  C  30   C
3  B  B  40   C
4  X  X   C  50
Run Code Online (Sandbox Code Playgroud)

选项1是我们删除XColumn H和预期的输出将是:

   G  H   I   J
0  X  B  10
1  B  A  20   B
2  A  C  30   C
3  B  B  40   C
4  X  C  50
Run Code Online (Sandbox Code Playgroud)

选项2是我们合并X进入Column G-H,预期输出将是:

   G   H   I   J
0  XX  B  10
1  B   A  20   B
2  A   C  30   C
3  B   B  40   C
4  XX  C  50
Run Code Online (Sandbox Code Playgroud)

我玩过df = df.drop(df.H == 'X')但这会删除整行.

Hal*_*Ali 5

选项1:

您可以将符合条件的行的值向左移动df.H == 'X'

具有以下变量定义:

hij = ['H', 'I', 'J']
x = df.H=='X'
Run Code Online (Sandbox Code Playgroud)

我们可以简洁地写出轮班分配。

df.loc[x, hij] = df.loc[x, hij].apply(lambda x: x.shift(-1), axis=1)
outputs:
    G   H   I   J
0   X   B   10  NaN
1   B   A   20  B
2   A   C   30  C
3   B   B   40  C
4   X   C   50  NaN
Run Code Online (Sandbox Code Playgroud)

选项2:

原理相同,但需要两个声明。

我们可以连接HG

df.loc[x, 'G'] = df.loc[x, 'G'] + df.loc[x, 'H']
# df.loc[x, 'G'] = df.loc[x, ['G, 'H']].sum(axis=1)
# or df.loc[x, ['G', 'H']].apply(np.sum, axis=1)
# or df.loc[x, 'G'] = df.loc[x, ['G', 'H']].apply(lambda x: (x + x.shift(-1))[0], axis=1)
Run Code Online (Sandbox Code Playgroud)

并按照选项 1 进行移位

df.loc[x, hij] = df.loc[x, hij].apply(lambda x: x.shift(-1), axis=1)
final output:
    G   H   I   J
0   XX  B   10  NaN
1   B   A   20  B
2   A   C   30  C
3   B   B   40  C
4   XX  C   50  NaN
Run Code Online (Sandbox Code Playgroud)