繁体   English   中英

Pandas dataframe 检查字符串的左侧部分是否与列中的另一个条目匹配

[英]Pandas dataframe check if left part of a string matches another entry in a column

我有以下 csv 文件:

Column1;Column2;Column3;Column4
A;B;6;6200
B;D;5;5000
E;F;6;5100
F;F;6;6200

现在我想检查column4是否总是以“ 6 ”开头, column3是否有条目6 如果这不匹配,我想打印一条消息 反之亦然:如果column4不是以“ 6 ”开头,但column3有一个条目6 两列都是字符串。

我试过了:

if ((df[df["Column3"] == "6"] and df['Column4'].str[0:1] <> "6") or (df[df["Column3"] <> "6"] and df['Column4'].str[0:1] == "6")):
    print("Error")

但不起作用。 我错过了什么?

您可以使用两个 boolean 掩码并检查其身份:

out = df[df['Column3'].eq('6') == df['Column4'].str.startswith('6')]

注意。 假设你有字符串。 如果不是,请在切片后立即添加 `.astype(str) 。

out = df[df['Column3'].astype(str).eq('6') == df['Column4'].astype(str).str.startswith('6')]

Output:

0       A       B        6     6200
1       B       D        5     5000
3       F       F        6     6200

打印消息:

m = df['Column3'].eq('6') != df['Column4'].str.startswith('6')
if m.any():
    print(f'Error: row(s) {",".join(m[m].index.astype(str))} are invalid')

Output:

Error: row(s) 2 are invalid
import pandas as pd

df = pd.read_clipboard(sep=';').astype(str) # Your frame here

out = df.loc[df["Column3"] == "6", "Column4"].str[0].eq("6").all()
# out is True if all values in column 4 start with 6 when the corresponding cell in column 3 is "6", False otherwise.

# Example usage:
if not out:
    print("Caution!")

尝试这个:

import pandas as pd
df = pd.DataFrame({'Column1':['A','B','E','F'],'Column2':['B','D','F','F'], 'Column3':['6','5','6','6'], 'Column4':['6200','5000','5100','6200']})
df.loc[(df['Column3'].str.slice(stop=1)!=df['Column4'].str.slice(stop=1))] #Select rows where first char is not the same in column3 vs 4

#  Column1 Column2 Column3 Column4
#       E       F       6    5100

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM