为了账号安全,请及时绑定邮箱和手机立即绑定

基于一列元素在熊猫上创建新列

基于一列元素在熊猫上创建新列

慕盖茨4494581 2023-02-15 17:30:43
我有一个带有这样列的数据框:    column_1                    0   0.25 / 0 / 0.25 / -0.25     1   -0.25 / 0 /1                2   0 / -0.5 / -0.25            3   1/ 0.25 / -0.75             每行由连续数字链组成(由 / 分隔)我想创建 2 个新列,并只保留第一个元素和最后一个元素,如下例所示    column_1                     new_column_1st_element   new_column_last_element0   0.25 / 0 / 0.25 / -0.25      0.25                     -0.251   -0.25 / 0 /1                 -0.25                    12   0 / -0.5 / -0.25             0                        -0.253   1/ 0.25 / -0.75              1                        -0.75
查看完整描述

3 回答

?
杨__羊羊

TA贡献1943条经验 获得超7个赞

干得好:


df['new_column_1st_element'] = df.column_1.str.split('/').str[0]

df['new_column_last_element'] = df.column_1.str.split('/').str[-1]

输出


                  column_1 new_column_1st_element new_column_last_element

0  0.25 / 0 / 0.25 / -0.25                  0.25                    -0.25

1             -0.25 / 0 /1                 -0.25                        1

2         0 / -0.5 / -0.25                     0                    -0.25

3          1/ 0.25 / -0.75                      1                   -0.75


查看完整回答
反对 回复 2023-02-15
?
慕沐林林

TA贡献2016条经验 获得超9个赞

假设column_1有字符串数据类型的数据

df['new_column_1st_element'] = df.apply(lambda row: row['column_1'].split('/')[0], axis = 1)

同样,这可以为new_column_last_element


查看完整回答
反对 回复 2023-02-15
?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

Series.str.extract与给定的正则表达式模式一起使用:

df[['first', 'last']] = df['column_1'].str.extract(r'([^/]+).*?([^/]+)$')

结果:

# print(df)


column_1                    first     last

0  0.25 / 0 / 0.25 / -0.25   0.25    -0.25

1             -0.25 / 0 /1  -0.25        1

2         0 / -0.5 / -0.25      0    -0.25

3          1/ 0.25 / -0.75      1    -0.75

您可以测试regex模式here



查看完整回答
反对 回复 2023-02-15
  • 3 回答
  • 0 关注
  • 103 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号