英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论