2 回答
TA贡献1828条经验 获得超6个赞
非循环解决方案numpy.where
:
df['new_col'] = np.where(df.index.str[0].str.isalpha() &
~df.index.str.startswith("I0"), 'P', 'C')
您的解决方案 -x[0]从中删除x[0].startswith("I0")- 它测试第一个值,如果不是I0,则始终是True:
df['new_col'] = ['P' if (x[0].isalpha() and not x.startswith("I0"))
else 'C' for x in df.index]
测试:
df = pd.DataFrame({'A': {'AA00001': 1.3253365856660808,
'I00002': 1.6147800817881086,
'IR0003': 1.1414534979918203,
'00004': 0.9183004454646491,
'**00005': 1.1896061362142527,
'I00007': 0.46638312473267185}}
)
df['new_col'] = np.where(df.index.str[0].str.isalpha() &
~df.index.str.startswith("I0"), 'P', 'C')
df['new_col1'] = ['P' if (x[0].isalpha() and not x.startswith("I0"))
else 'C' for x in df.index]
print (df)
A new_col new_col1
**00005 1.189606 C C
00004 0.918300 C C
AA00001 1.325337 P P
I00002 1.614780 C C
I00007 0.466383 C C
IR0003 1.141453 P P
TA贡献1780条经验 获得超5个赞
您正在检查x[0].startswith("I0")
您的代码,这是不正确的尝试这个(检查x.startswith("I0")
)
df['new_col'] = ['P' if (x[0].isalpha() and not x.startswith("I0")) else 'C' for x in df.index]
添加回答
举报