如何反转数据帧中的字符串?

2024-10-05 10:44:46 发布

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

我的数据帧就像

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'

我怎样才能解决这个问题?你知道吗


Tags: lambdaiddfcol1splitapplystrmichael
3条回答

使用^{}

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

It gives me an error,

这是因为str.contains(", ")返回一个布尔序列,而它没有方法split。你知道吗

无论如何,试试看

df.col1.str.split(',').str[1] + ',' + df.col1.str.split(',').str[0]

修复代码np.where

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

相关问题 更多 >

    热门问题