基于现有列下的值创建新列

2024-04-18 12:13:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据数据框的下一个索引中已有的值在数据框中创建一个新列。因此,数据帧如下所示:

col1 col2
A   Test
A   Test1
A   Test2
B   BTest
B   BTest1

因此,在这种情况下,每个新字母的值都必须改变,最终的数据帧应该如下所示:

A  Test  Test1
A  Test1  Test2
A  Test2  
B  BTest  BTest1
B  BTest1  

我想稍后在有向图中绘制这个,这就是为什么我需要这样做。有没有想过在不写exspensive for循环的情况下执行这个?你知道吗


Tags: 数据testfor字母绘制情况col2col1
2条回答

我想这是你想做的自我加入。你知道吗

import pandas as pd

df = pd.read_clipboard()

df = df.sort_values(['col1', 'col2']) 

df.reset_index() \
                .merge(df.shift(-1).reset_index(), \
                       how='left', \
                       left_on = ['index', 'col1'], \
                       right_on = ['index', 'col1'])\
               .drop('index', axis=1)

输出:

Out[176]: 
  col1  col2_x  col2_y
0    A    Test   Test1
1    A   Test1   Test2
2    A   Test2     NaN
3    B   BTest  BTest1
4    B  BTest1     NaN

使用groupby并将列值上移1(因此,shift(-1)):

df.groupby('col1')['col2'].shift(-1)                                                                                   

0     Test1
1     Test2
2       NaN
3    BTest1
4       NaN
Name: col2, dtype: object

df['new'] = df.groupby('col1')['col2'].shift(-1)
df

  col1    col2     new
0    A    Test   Test1
1    A   Test1   Test2
2    A   Test2     NaN
3    B   BTest  BTest1
4    B  BTest1     NaN

相关问题 更多 >