输入数据:
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它将告诉我哪些行是真行还是假行。但我不想按我所需要的方式填塞。有什么帮助吗?谢谢!
发布于 2019-08-28 11:44:48
在掩码中使用Series.where并向前填充缺失的值:
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另一种使用Series.str.extract和正向填充缺失值的解决方案:
df['B'] = df['A'].str.extract(r'^(NBN\s+\d\.\d|NBN\s+\d)', expand=False).ffill()https://stackoverflow.com/questions/57691610
复制相似问题