问题:检查pandas数据框索引中是否存在值
我敢肯定有一个明显的方法可以做到这一点,但是现在还不能想到任何光滑的东西。
基本上不是引发异常,而是要获取True
或False
查看pandas df
索引中是否存在值。
import pandas as pd
df = pd.DataFrame({'test':[1,2,3,4]}, index=['a','b','c','d'])
df.loc['g'] # (should give False)
我现在工作的是以下内容
sum(df.index == 'g')
I am sure there is an obvious way to do this but cant think of anything slick right now.
Basically instead of raising exception I would like to get True
or False
to see if a value exists in pandas df
index.
import pandas as pd
df = pd.DataFrame({'test':[1,2,3,4]}, index=['a','b','c','d'])
df.loc['g'] # (should give False)
What I have working now is the following
sum(df.index == 'g')
回答 0
这应该可以解决问题
'g' in df.index
This should do the trick
'g' in df.index
回答 1
仅供参考,这是我一直在寻找的东西,您可以通过附加“ .values”方法来测试值或索引中是否存在,例如
g in df.<your selected field>.values
g in df.index.values
我发现添加“ .values”以获取简单的列表或ndarray会使存在或“输入”检查与其他python工具一起运行更为流畅。只是以为我会把那个扔给别人。
Just for reference as it was something I was looking for, you can test for presence within the values or the index by appending the “.values” method, e.g.
g in df.<your selected field>.values
g in df.index.values
I find that adding the “.values” to get a simple list or ndarray out makes exist or “in” checks run more smoothly with the other python tools. Just thought I’d toss that out there for people.
回答 2
多索引的工作方式与单索引略有不同。这是多索引数据框的一些方法。
df = pd.DataFrame({'col1': ['a', 'b','c', 'd'], 'col2': ['X','X','Y', 'Y'], 'col3': [1, 2, 3, 4]}, columns=['col1', 'col2', 'col3'])
df = df.set_index(['col1', 'col2'])
in df.index
仅在检查单个索引值时才适用于第一级。
'a' in df.index # True
'X' in df.index # False
检查df.index.levels
其他级别。
'a' in df.index.levels[0] # True
'X' in df.index.levels[1] # True
签入df.index
索引组合元组。
('a', 'X') in df.index # True
('a', 'Y') in df.index # False
Multi index works a little different from single index. Here are some methods for multi-indexed dataframe.
df = pd.DataFrame({'col1': ['a', 'b','c', 'd'], 'col2': ['X','X','Y', 'Y'], 'col3': [1, 2, 3, 4]}, columns=['col1', 'col2', 'col3'])
df = df.set_index(['col1', 'col2'])
in df.index
works for the first level only when checking single index value.
'a' in df.index # True
'X' in df.index # False
Check df.index.levels
for other levels.
'a' in df.index.levels[0] # True
'X' in df.index.levels[1] # True
Check in df.index
for an index combination tuple.
('a', 'X') in df.index # True
('a', 'Y') in df.index # False
回答 3
与DataFrame:df_data
>>> df_data
id name value
0 a ampha 1
1 b beta 2
2 c ce 3
我试过了:
>>> getattr(df_data, 'value').isin([1]).any()
True
>>> getattr(df_data, 'value').isin(['1']).any()
True
但:
>>> 1 in getattr(df_data, 'value')
True
>>> '1' in getattr(df_data, 'value')
False
很有趣:D
with DataFrame: df_data
>>> df_data
id name value
0 a ampha 1
1 b beta 2
2 c ce 3
I tried:
>>> getattr(df_data, 'value').isin([1]).any()
True
>>> getattr(df_data, 'value').isin(['1']).any()
True
but:
>>> 1 in getattr(df_data, 'value')
True
>>> '1' in getattr(df_data, 'value')
False
So fun :D
回答 4
df = pandas.DataFrame({'g':[1]}, index=['isStop'])
#df.loc['g']
if 'g' in df.index:
print("find g")
if 'isStop' in df.index:
print("find a")
df = pandas.DataFrame({'g':[1]}, index=['isStop'])
#df.loc['g']
if 'g' in df.index:
print("find g")
if 'isStop' in df.index:
print("find a")
回答 5
下面的代码不打印布尔值,但允许按索引对数据框进行子集设置…我知道这可能不是解决问题的最有效方法,但是我(1)喜欢这种读取方式,并且(2)您可以轻松地进行子集化df2中存在df1索引的位置:
df3 = df1[df1.index.isin(df2.index)]
或df2中不存在df1索引的地方…
df3 = df1[~df1.index.isin(df2.index)]
Code below does not print boolean, but allows for dataframe subsetting by index… I understand this is likely not the most efficient way to solve the problem, but I (1) like the way this reads and (2) you can easily subset where df1 index exists in df2:
df3 = df1[df1.index.isin(df2.index)]
or where df1 index does not exist in df2…
df3 = df1[~df1.index.isin(df2.index)]