gpt4 book ai didi

python - 检查列内的字符串错误行为 - Pandas

转载 作者:行者123 更新时间:2023-12-04 00:20:41 25 4
gpt4 key购买 nike

我有以下数据框:

import pandas as pd 

df = pd.DataFrame ({
'Name':['Unable host=test1, status=c0000192','Unable host=test2, status=22228001','Unable host=test3, status=c000018d'],
'Error':['NaN','NaN','NaN']
})


print(df)
Name Error
0 Unable host=test1, status=c0000192 NaN
1 Unable host=test2, status=22228001 NaN
2 Unable host=test3, status=c000018d NaN

代码应遵循以下 if 语句:

import pandas as pd 

df = pd.DataFrame ({
'Name':['Unable host=test1, status=c0000192','Unable host=test2, status=22228001','Unable host=test3, status=c000018d'],
'Error':['NaN','NaN','NaN']
})

if df['Name'].str.contains('status=c000018d').any():
df['Error'] = 'Trust Failure'

elif df['Name'].str.contains('status=22228001').any():
df['Error'] = 'No creds'

else:
df['Error'] = 'Other'

print(df)

输出应该是:

                                   Name          Error
0 Unable host=test1, status=c0000192 Other
1 Unable host=test2, status=22228001 No creds
2 Unable host=test3, status=c000018d Trust Failure

相反,我得到:

                                   Name          Error
0 Unable host=test1, status=c0000192 Trust Failure
1 Unable host=test2, status=22228001 Trust Failure
2 Unable host=test3, status=c000018d Trust Failure

为什么会这样?这就像第一个 if 语句匹配所有内容。

最佳答案

我认为你在这里混合了一些东西,试试这个方法:

df.loc[df['Name'].str.contains('status=c000018d'), 'Error'] = 'Trust Failure'
df.loc[df['Name'].str.contains('status=22228001'), 'Error'] = 'No creds'
df.loc[df['Name'] == 'NaN', 'Error'] = 'Other'

您正在执行的操作在第一个 if 语句中返回 true,并用“信任失败”填充所有值。

关于python - 检查列内的字符串错误行为 - Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60933796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com