用条件填充行

2024-06-16 12:43:15 发布

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

输入数据:

df=pd.DataFrame({'A':['NBN 3','test text1','test text2','NBN 3.1 new text','test 
1','test 2']},columns=['A','B'])
    print(df)
                  A  B
0             NBN 3
1        test text1
2        test text2
3  NBN 3.1 new text
4            test 1
5            test 2

我需要创建一个由值df['B']= NBN and number填充的新列 我想从这个df的上到下,用第一个NBN值unil填充行,下一个NBN值就会出现。你知道吗

预期产量:

                  A  B
0             NBN 3  NBN 3
1        test text1  NBN 3
2        test text2  NBN 3
3  NBN 3.1 new text  NBN 3.1
4            test 1  NBN 3.1
5            test 2  NBN 3.1

等等。你知道吗

现在我只能用

df['B'] = df['A'].str.contains(r'^NBN \d|^NBN \d\.\d')

                  A      B
0             NBN 3   True
1        test text1  False
2        test text2  False
3  NBN 3.1 new text   True
4            test 1  False
5            test 2  False

它会告诉我哪些行是真的或不是。但我不能按我需要的方式填充。 有什么帮助吗?谢谢!你知道吗


Tags: columnsand数据texttestfalsetruedataframe
1条回答
网友
1楼 · 发布于 2024-06-16 12:43:15

在掩码中使用^{},并向前填充缺少的值:

df['B'] =  df['A'].where(df['A'].str.contains('NBN')).ffill()

#your solution should be changed
#df['B'] =  df['A'].where(df['A'].str.contains(r'^NBN \d|^NBN \d\.\d')).ffill()
print(df)

            A        B
0       NBN 3    NBN 3
1  test text1    NBN 3
2  test text2    NBN 3
3     NBN 3.1  NBN 3.1
4      test 1  NBN 3.1
5      test 2  NBN 3.1

另一个具有^{}和正向填充缺失值的解决方案:

df['B'] = df['A'].str.extract(r'^(NBN\s+\d\.\d|NBN\s+\d)', expand=False).ffill()

相关问题 更多 >