【问题标题】:Parse the column value and save the first section in new column解析列值并将第一部分保存在新列中
【发布时间】:2023-02-01 19:26:27
【问题描述】:

我需要解析数据框中的列值,并将第一个解析的部分保存在一个新列中,如果它有一个像“-”这样的解析分隔符,如果不留空

raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
'code': ['01-02-11-55-00115','11-02-11-55-00445','test', '31-0t-11-55-00115'],
'favorite_color': ['blue', 'blue', 'yellow', 'green'],  
'grade': [88, 92, 95, 70]}
df = pd.DataFrame(raw_data)
df.head()

添加一个具有第一个已解析部分的新列,预期的列值为: 01 11 无效的 31

【问题讨论】:

    标签: python p-lang


    【解决方案1】:
    df['parsed'] = df['code'].apply(lambda x: x.split('-')[0] if '-' in x else 'null')
    

    将输出:

                   name               code favorite_color  grade parsed
    0    Willard Morris  01-02-11-55-00115           blue     88     01
    1       Al Jennings  11-02-11-55-00445           blue     92     11
    2      Omar Mullins               test         yellow     95   null
    3  Spencer McDaniel  31-0t-11-55-00115          green     70     31
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多