Pandas 按行检查元素字符串是否以其他元素的字符串开头(2 个不同的列)

Pandas row-wise check if element string starts with string from other element (2 different columns)

我收到了一个包含 2 列(简化版)的 .csv 文件。一列包含数据,另一列包含文件名。不幸的是,这个文件名可能不正确,我必须通过比较日期和文件名来确定。

我想要的

# initial situation
d = {
    'call_date': ["20200102-09", "20191203-04", "20200103-10"],
    'filename': ["20200102-09xx.wav", "20200102-10yy.wav", "20200103-10zz.wav"]
}
df = pd.DataFrame(data=d)
print(df)

#      call_date           filename
# 0  20200102-09  20200102-09xx.wav
# 1  20191203-04  20200102-10yy.wav
# 2  20200103-10  20200103-10zz.wav
...

# desired result
print(pd.Series([True, False, True]))
# 0     True
# 1    False
# 2     True
# dtype: bool

有了预期的结果,我可以计算出我有多少错误文件并过滤 DataFrame 以仅包含有效条目。

我试过的

通常比较会这样进行:

# True / False
df["call_date"] == df["filename"]
# filter DF
df[df["call_date"] == df["filename"]]

Pandas 有一个 pandas.Series.str.startswith 函数,但是它只适用于单个字符串而不适用于诸如:

df["filename"].str.startswith(df["call_date"])

# 0   NaN
# 1   NaN
# 2   NaN
# Name: filename, dtype: float64

问题

如何逐行比较 "filename" 列中的元素是否以 "call_date" 列中的字符串开头?

将列表理解与 startswith 结合使用 - 输出为列表,可用于 boolean indexing

的过滤
m = [x.startswith(y) for x, y in df[['filename','call_date']].values]

或:

m = [x.startswith(y) for x, y in zip(df['filename'], df['call_date'])]

print (m)
[True, False, True]

另一种解决方案,但速度较慢:

m = df.apply(lambda x: x['filename'].startswith(x['call_date']), axis=1)
print (m)
0     True
1    False
2     True
dtype: bool

执行:

df['is_correct'] = df.apply(lambda x: x['filename'].startswith(x['call_date']),axis=1)

那么,总结一下你答对了几个:

df['is_correct'].sum()