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

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

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

问题

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

A
AB101CD
AB101CD
AB101CD

结果:

A
101
101
101
英文:

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

A
AB101CD
AB101CD
AB101CD

result:

A
101
101
101

答案1

得分: 0

你可以使用 df.column.apply

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

这会得到以下结果:

0    101
1    101
2    101
Name: A, dtype: object

你可以将其设置为列:

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

You could use df.column.apply

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

This gives:

0    101
1    101
2    101
Name: A, dtype: object

You could set it as column:

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

答案2

得分: 0

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

str = "AB101CD"

print(str[2:5])

output will be "101"

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

mylist = ["A",
          "AB101CD",
          "AB101CD",
          "AB101CD"]

list2 = []

for i in mylist:
    #it wont return anything for the first element, "A", so you should define what do you want to do here for non-suitable elements
    
    #print
    print(i[2:5])

    #get into another list
    list2.append(i[2:5])
英文:

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

str = "AB101CD"

print(str[2:5])

output will be "101"

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

mylist = ["A",
          "AB101CD",
          "AB101CD",
          "AB101CD"]

list2 = []

for i in mylist:
    #it wont return anything for the first element, "A", so you should define what do you want to do here for non-suitable elements
    
    #print
    print(i[2:5])

    #get into another list
    list2.append(i[2:5])

答案3

得分: 0

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

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

输出

     A
0  101
1  101
2  101
英文:

You can slice the column with broadcasting

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

Output

     A
0  101
1  101
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:

确定