获取列中每个条目中字符串的索引2-4。

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

How do I get the index 2-4 of a String in each entry of a column?

问题

我需要为数据框中的每个条目提取字符串的索引2-4。例如:

  1. A
  2. AB101CD
  3. AB101CD
  4. AB101CD

结果:

  1. A
  2. 101
  3. 101
  4. 101
英文:

I have a column in a dataframe and need for every entry just the index 2-4 of the string.
For example

  1. A
  2. AB101CD
  3. AB101CD
  4. AB101CD

result:

  1. A
  2. 101
  3. 101
  4. 101

答案1

得分: 0

你可以使用 df.column.apply

  1. import pandas as pd
  2. a = ['AB101CD','AB101CD','AB101CD']
  3. df = pd.DataFrame(a)
  4. df.columns = ['A']
  5. df.A.apply(lambda x:x[2:5])

这会得到以下结果:

  1. 0 101
  2. 1 101
  3. 2 101
  4. Name: A, dtype: object

你可以将其设置为列:

  1. df.A = df.A.apply(lambda x:x[2:5])
英文:

You could use df.column.apply

  1. import pandas as pd
  2. a = ['AB101CD','AB101CD','AB101CD']
  3. df = pd.DataFrame(a)
  4. df.columns = ['A']
  5. df.A.apply(lambda x:x[2:5])

This gives:

  1. 0 101
  2. 1 101
  3. 2 101
  4. Name: A, dtype: object

You could set it as column:

  1. df.A = df.A.apply(lambda x:x[2:5])

答案2

得分: 0

You can get a strings substring by using {string_variable}[{index1}:{index2}]

  1. str = "AB101CD"
  2. print(str[2:5])

output will be "101"

then you can apply this to your list or whatever with a for loop for example:

  1. mylist = ["A",
  2. "AB101CD",
  3. "AB101CD",
  4. "AB101CD"]
  5. list2 = []
  6. for i in mylist:
  7. #it wont return anything for the first element, "A", so you should define what do you want to do here for non-suitable elements
  8. #print
  9. print(i[2:5])
  10. #get into another list
  11. list2.append(i[2:5])
英文:

You can get a strings substring by using {string_variable}[{index1}:{index2}]

  1. str = "AB101CD"
  2. print(str[2:5])

output will be "101"

then you can apply this to your list or whatever with a for loop for example:

  1. mylist = ["A",
  2. "AB101CD",
  3. "AB101CD",
  4. "AB101CD"]
  5. list2 = []
  6. for i in mylist:
  7. #it wont return anything for the first element, "A", so you should define what do you want to do here for non-suitable elements
  8. #print
  9. print(i[2:5])
  10. #get into another list
  11. list2.append(i[2:5])

答案3

得分: 0

你可以使用广播操作来切割列

  1. df['A'] = df['A'].str[2:5]

输出

  1. A
  2. 0 101
  3. 1 101
  4. 2 101
英文:

You can slice the column with broadcasting

  1. df['A'] = df['A'].str[2:5]

Output

  1. A
  2. 0 101
  3. 1 101
  4. 2 101

huangapple
  • 本文由 发表于 2023年4月17日 15:41:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032745.html
匿名

发表评论

匿名网友

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

确定