检查Panda DataFrame单元格是否包含符号



我有一个5666行的数据帧。我需要检查它是否包含符号#,如果是,取出我添加到它的符号_。现在,我正在添加一个列note_features['chord_label'] = note_features['bass'] + '_' + 'M'

我有一行将等于F_M,这很好,但我有另一行等于F#_M。我想去掉_,使它等于F#M。我该怎么做?

谢谢

df = pd.DataFrame({"Column":["F#_M","F_M"]})
output
Column
0   F#_M
1   F_M
df.Column.apply(lambda x: x.replace("#","") if "#" in x else x)
# output
0    F_M
1    F_M
Name: Column
OR 
df.Column.apply(lambda x: x.replace("_","") if "#" in x else x)
# output
0    F#M
1    F_M
Name: Column

这有助于你实现转变吗?

apply的作用是在每一行上应用一个特定的函数。我们的函数是lambdareplacesomething选择的character。在我们的例子中,它是一个_乘以empty字符串。CCD_ 15<>如果该行包含#,请将其替换为emptyELSE保持x原样。

以下操作将起作用(即使字符串中存在其他'#",但如果存在多个'#_',则只考虑第一次出现(:

note_features['chord_label']=note_features['chord_label'].apply(lambda x: x[:x.index('#_')+1]+x[x.index('#')+2:] if '#_' in x else x)

最新更新