Pandas: ตรวจสอบว่าสตริงมีหลายสตริงย่อยหรือไม่


คุณสามารถใช้วิธีการต่อไปนี้เพื่อตรวจสอบว่าสตริงใน Pandas DataFrame มีหลายสตริงย่อยหรือไม่:

วิธีที่ 1: ตรวจสอบว่าสตริงประกอบด้วยสตริงย่อยหลายรายการหรือไม่

 df[' string_column ']. str . contains (' | ' .join ([' string1 ',' string2 ']))

วิธีที่ 2: ตรวจสอบว่าสตริงประกอบด้วยสตริงย่อยหลายรายการหรือไม่

 df[' string_column ']. str . contains ( r'^(?=.*string1)(?=.*string2)' )

ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีในทางปฏิบัติกับ Pandas DataFrame ต่อไปนี้:

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['Good East Team', 'Good West Team', 'Great East Team',
                             'Great West Team', 'Bad East Team', 'Bad West Team'],
                   ' points ': [93, 99, 105, 110, 85, 88]})

#view DataFrame
print (df)

              team points
0 Good East Team 93
1 Good West Team 99
2 Great East Team 105
3 Great West Team 110
4 Bad East Team 85
5 Bad West Team 88

ตัวอย่าง ที่ 1: ตรวจสอบว่าสตริงมีสตริงย่อยหลายรายการหรือไม่

เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อตรวจสอบว่าแต่ละสตริงในคอลัมน์ ทีม มีสตริงย่อย “ดี” หรือ “เป็น”:

 #create new column that checks if each team name contains 'Good' or 'East'
df[' good_or_east '] = df[' team ']. str . contains (' | ' .join ([' Good ',' East ']))

#view updated DataFrame
print (df)

              team points good_or_east
0 Good East Team 93 True
1 Good West Team 99 True
2 Great East Team 105 True
3 Great West Team 110 False
4 Bad East Team 85 True
5 Bad West Team 88 False

คอลัมน์ good_or_east ใหม่จะส่งกลับค่าต่อไปนี้:

  • เป็นจริง หากทีมมีคำว่า “ดี” หรือ “เป็น”
  • เท็จ หากทีมไม่มีทั้ง “ดี” หรือ “เป็น”

หมายเหตุ : | โอเปอเรเตอร์หมายถึง “หรือ” ในภาษาหมีแพนด้า

ตัวอย่างที่ 2 : ตรวจสอบว่าสตริงมีหลายสตริงย่อยหรือไม่

เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อตรวจสอบว่าแต่ละสตริงในคอลัมน์ ทีม มีสตริงย่อย “Good” และ “Is” หรือไม่:

 #create new column that checks if each team name contains 'Good' and 'East'
df[' good_and_east '] = df[' team ']. str . contains ( r'^(?=.*Good)(?=.*East)' )

#view updated DataFrame
print (df)

              team points good_and_east
0 Good East Team 93 True
1 Good West Team 99 False
2 Great East Team 105 False
3 Great West Team 110 False
4 Bad East Team 85 False
5 Bad West Team 88 False

คอลัมน์ใหม่ good_and_east ส่งคืนค่าต่อไปนี้:

  • เป็นจริง หากทีมมีคำว่า “ดี” และ “เป็น”
  • เท็จ หากทีมไม่มีคำว่า “ดี” และ “เป็น”

โปรดทราบว่าจะมีการส่งคืนค่า True เพียงค่าเดียวเนื่องจากมีชื่อทีมเพียงชื่อเดียวที่มีสตริงย่อย “Good” และ สตริงย่อย “East”

แหล่งข้อมูลเพิ่มเติม

บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำงานทั่วไปอื่นๆ ในแพนด้า:

Pandas: เพิ่มคอลัมน์จาก DataFrame หนึ่งไปยังอีก DataFrame
นุ่น: รับแถวที่ไม่ได้อยู่ใน DataFrame อื่น
Pandas: วิธีตรวจสอบว่าหลายคอลัมน์เท่ากันหรือไม่

เพิ่มความคิดเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *