将一个列的特定部分值添加到另一个列

huangapple go评论104阅读模式
英文:

add specific part of one column values to another column

问题

以下是翻译好的代码部分:

  1. import pandas as pd
  2. data = {'existing_indiv': ['stac.Altered', 'MASO.MHD'], 'queries': ['modify', 'change']}
  3. df = pd.DataFrame(data)

你想要的操作是将periodperiod之前的word添加到queries列的值的开头。

期望的结果:

  1. existing_indiv queries
  2. 0 stac.Altered stac.modify
  3. 1 MASO.MHD MASO.change

有什么想法吗?

英文:

I have the following dataframe

  1. import pandas as pd
  2. data = {'existing_indiv': ['stac.Altered', 'MASO.MHD'], 'queries': ['modify', 'change']}
  3. df = pd.DataFrame(data)
  4. existing_indiv queries
  5. 0 stac.Altered modify
  6. 1 MASO.MHD change

I want to add the period and the word before the period to the beginning of the values of the queries column

Expected outcome:

  1. existing_indiv queries
  2. 0 stac.Altered stac.modify
  3. 1 MASO.MHD MASO.change

Any ideas?

答案1

得分: 3

你可以使用.str.extract和正则表达式^([^.]+\.)来提取第一个.之前的所有内容:

  1. df.queries = df.existing_indiv.str.extract('^([^.]+\\.)', expand=False) + df.queries
  2. df
  3. existing_indiv queries
  4. 0 stac.Altered stac.modify
  5. 1 MASO.MHD MASO.change

如果你更喜欢使用.str.split

  1. df.existing_indiv.str.split('.').str[0] + '.' + df.queries
  2. 0 stac.modify
  3. 1 MASO.change
  4. dtype: object
英文:

You can use .str.extract and regex ^([^.]+\.) to extract everything before the first .:

  1. df.queries = df.existing_indiv.str.extract('^([^.]+\.)', expand=False) + df.queries
  2. df
  3. existing_indiv queries
  4. 0 stac.Altered stac.modify
  5. 1 MASO.MHD MASO.change

If you prefer .str.split:

  1. df.existing_indiv.str.split('.').str[0] + '.' + df.queries
  2. 0 stac.modify
  3. 1 MASO.change
  4. dtype: object

huangapple
  • 本文由 发表于 2023年1月9日 04:54:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定