Проверить, начинается ли столбец с заданной строки в Pandas DataFrame?

Опубликовано: 27 Марта, 2022

In this program, we are trying to check whether the specified column in the given data frame starts with specified string or not. Let us try to understand this using an example suppose we have a dataset named student_id, date_of_joining, branch. 
Example:

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

Выход:

Теперь мы хотим знать, начинается ли 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 (), чтобы проверить, начинаются ли значения в столбце с данной строки. Метод .startswith () в Python возвращает True, если строка начинается с указанного значения, в противном случае возвращает False .

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.