Skip to main content
 首页 » 编程设计

python之如何反转 Pandas 数据框中的字符串

2025年05月04日19cmt

我的数据框是这样的

ID   col1 
1    Michael Owen 
2    Stephen Curry 
3    Messi, Lionel 
4    James, LeBron 

我试图颠倒那些被 ", " 分割的名字的顺序。

我的代码是,

df['col1'] = df.col1.str.split().apply(lambda x: ', '.join(x[::-1]))

但它会反转所有行,即使名称被 "" 分割。

ID   col1 
1    Owen, Michael 
2    Curry, Stephen 
3    Lionel, Messi 
4    LeBron, James 

然后我试了一下

df.loc[df['col1'].str.contains(", ").split("col1")].apply(lambda x: ', '.join(x[::- 1]))

它给我一个错误,

AttributeError: 'Series' object has no attribute 'split' 

我该如何解决这个问题?

请您参考如下方法:

使用Series.where :

df['col1']=( df.col1.str.split() 
              .apply(lambda x: ', '.join(x[::-1]).rstrip(',')) 
              .where(df['col1'].str.contains(','),df['col1']) ) 

   ID           col1 
0   1   Michael Owen 
1   2  Stephen Curry 
2   3  Lionel, Messi 
3   4  LeBron, James 

如果你想删除 ','

df['col1']=( df.col1.str.split() 
              .apply(lambda x: ', '.join(x[::-1]).rstrip(',')) 
              .where(df['col1'].str.contains(','),df['col1'])  
              .str.replace(',','') ) 

   ID           col1 
0   1   Michael Owen 
1   2  Stephen Curry 
2   3  Lionel  Messi 
3   4  LeBron  James