如何检查列名是在字符串的最后还是前面(python)?

How to check if the column name is at the last or in the front of a string (python)?

我是 pandas 的新手。我不知道该列在字符串中的最后一个或第一个位置。假设我有一个字符串 str = "000*999bikes",其中 bikes 是 df 的列名,现在我想检查该列的位置是在第一个还是最后一个

我的代码:

str = "000*999bikes"
df =
  bikes cars
0  12    23
1  34    67
3  56    90

现在列名 bikes 位于字符串的最后。如何知道是不是在最后一次using if条件?

如果您只想要列名旁边的数字,可以使用以下代码检查每一列。

import pandas as pd

df = pd.DataFrame([[1,2],[2,2]],columns=['bikes','cars'])

strings = ["cars000*999","000*999bikes"]

for s in strings:
    for col in df.columns:
        if s.startswith(col):
            print(col, s[len(col) + 1])
        if s.endswith(col):
            print(col, s[-len(col) - 1])

输出:

cars 0
bikes 9

如果您的字符串在数据框中,那么您可以使用 pandas str operations 而不是循环。