检查一列是否以 Pandas DataFrame 中的给定字符串开头?
在这个程序中,我们试图检查给定数据框中的指定列是否以指定字符串开头。让我们尝试通过一个示例来理解这一点,假设我们有一个名为 student_id, date_of_joining, branch 的数据集。
例子:
Python3
#importing library pandas as pd
import pandas as pd
#creating data frame for student
df = pd.DataFrame({
'Student_id': ['TCS101','TCS103', 'PCS671',
'ECS881', 'MCS961'],
'date_of_joining': ['12/12/2016','07/12/2015',
'11/11/2011','09/12/2014',
'01/01/2017'],
'Branch': ['Computer Science','Computer Science',
'Petroleum','Electrical','Mechanical']
})
# printing the given data frame
df
Python3
#importing library pandas as pd
import pandas as pd
#creating data frame for student
df = pd.DataFrame({
'Student_id': ['TCS101','TCS103', 'PCS671',
'ECS881', 'MCS961'],
'date_of_joining': ['12/12/2016','07/12/2015',
'11/11/2011','09/12/2014',
'01/01/2017'],
'Branch': ['Computer Science','Computer Science',
'Petroleum','Electrical','Mechanical']
})
# joining new column in dataframe
# .startswith function used to check
df['student_id_starts_with_TCS'] = list(
map(lambda x: x.startswith('TCS'), df['Student_id']))
# printing new data frame
df
输出:
现在我们想知道 student_id 是否以 TCS 开头。现在让我们尝试使用Python来实现它
Python3
#importing library pandas as pd
import pandas as pd
#creating data frame for student
df = pd.DataFrame({
'Student_id': ['TCS101','TCS103', 'PCS671',
'ECS881', 'MCS961'],
'date_of_joining': ['12/12/2016','07/12/2015',
'11/11/2011','09/12/2014',
'01/01/2017'],
'Branch': ['Computer Science','Computer Science',
'Petroleum','Electrical','Mechanical']
})
# joining new column in dataframe
# .startswith function used to check
df['student_id_starts_with_TCS'] = list(
map(lambda x: x.startswith('TCS'), df['Student_id']))
# printing new data frame
df
输出:
在上面的代码中,我们使用了 .startswith()函数来检查列中的值是否以给定的字符串开头。如果字符串以指定值开头, Python中的.startswith()方法返回True ,否则返回False 。