Python 查询字符串值上的Dataframe列
我需要获取列开始处的值,这些值可以是Python 查询字符串值上的Dataframe列,python,pandas,dataframe,Python,Pandas,Dataframe,我需要获取列开始处的值,这些值可以是'MA',KP' 我正试图将我的数据帧查询链接为: df.loc[df['REFERRAL_GRP'].str.startswith("KP")==True | df['REFERRAL_GRP'].str.startswith("MA")==True] 这似乎不起作用,因为列包含pd.nan对象(空值) 查询本身是有效的,如何将这两个查询合并在一起 多谢各位 以下是我的错误消息: 回溯(最近一次呼叫最后一次): 调试探针,提示符40,第1行 文件“c:\
'MA',KP'
我正试图将我的数据帧查询链接为:
df.loc[df['REFERRAL_GRP'].str.startswith("KP")==True | df['REFERRAL_GRP'].str.startswith("MA")==True]
这似乎不起作用,因为列包含pd.nan对象(空值)
查询本身是有效的,如何将这两个查询合并在一起
多谢各位
以下是我的错误消息:
回溯(最近一次呼叫最后一次):
调试探针,提示符40,第1行
文件“c:\Python27\Lib\site packages\pandas\core\generic.py”,第892行,非零__
.format(self.\uuuuuu class.\uuuuuuu.\uuuuuu name.\uuuuuuuuu))
ValueError:序列的真值不明确。使用a.empty、a.bool()、a.item()、a.any()或a.all()。
试试numpy
这是一个我们经常看到的问题
df.loc[
# 2. This returns a whole lot of `True`s or `False`s
df['REFERRAL_GRP'].str.startswith("KP")==True
# 1. `|` is expecting a `True` or `False`
|
# 2. This returns a whole lot of `True`s or `False`s
df['REFERRAL_GRP'].str.startswith("MA")==True
]
通过用括号括起条件来修复它
df.loc[
# 1. Series of `True`s or `False`s
(df['REFERRAL_GRP'].str.startswith("KP")==True)
# 2. `|` is now a operator on `pd.Series` and is expecting `pd.Series`
|
# 1. Series of `True`s or `False`s
(df['REFERRAL_GRP'].str.startswith("MA")==True)
]
也就是说,我会这么做
df.loc[df.REFERRAL_GRP.str.match('^KP|MA')]
因此,列名需要以“MA”或“KP”开头,那么为什么要获取以“MA”或“KP”开头的值呢?您的问题和尝试相互矛盾。该表达式是否用于if、for或其他条件?
df.loc[df.REFERRAL_GRP.str.match('^KP|MA')]