如何根据Pandas中某列的值从DataFrame中选择行?
在SQL中,我会使用:
SELECT *
FROM table
WHERE column_name = some_value
如何根据Pandas中某列的值从DataFrame中选择行?
在SQL中,我会使用:
SELECT *
FROM table
WHERE column_name = some_value
当前回答
下面是一个简单的例子
from pandas import DataFrame
# Create data set
d = {'Revenue':[100,111,222],
'Cost':[333,444,555]}
df = DataFrame(d)
# mask = Return True when the value in column "Revenue" is equal to 111
mask = df['Revenue'] == 111
print mask
# Result:
# 0 False
# 1 True
# 2 False
# Name: Revenue, dtype: bool
# Select * FROM df WHERE Revenue = 111
df[mask]
# Result:
# Cost Revenue
# 1 444 111
其他回答
您可以在函数中使用loc(方括号):
# Series
s = pd.Series([1, 2, 3, 4])
s.loc[lambda x: x > 1]
# s[lambda x: x > 1]
输出:
1 2
2 3
3 4
dtype: int64
or
# DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [10, 20, 30]})
df.loc[lambda x: x['A'] > 1]
# df[lambda x: x['A'] > 1]
输出:
A B
1 2 20
2 3 30
很好的答案。只有当数据帧的大小接近百万行时,许多方法在使用df[df['col']==val]时往往需要很长时间。我希望“another_column”的所有可能值都对应于“some_column“中的特定值(在本例中是在字典中)。这起作用很快。
s=datetime.datetime.now()
my_dict={}
for i, my_key in enumerate(df['some_column'].values):
if i%100==0:
print(i) # to see the progress
if my_key not in my_dict.keys():
my_dict[my_key]={}
my_dict[my_key]['values']=[df.iloc[i]['another_column']]
else:
my_dict[my_key]['values'].append(df.iloc[i]['another_column'])
e=datetime.datetime.now()
print('operation took '+str(e-s)+' seconds')```
您也可以使用.apply:
df.apply(lambda row: row[df['B'].isin(['one','three'])])
它实际上按行工作(即,将函数应用于每一行)。
输出为
A B C D
0 foo one 0 0
1 bar one 1 2
3 bar three 3 6
6 foo one 6 12
7 foo three 7 14
结果与@unsubu提到的使用相同
df[[df['B'].isin(['one','three'])]]
要添加:您还可以执行df.groupby('column_name').get_group('column_desired_value').reset_index()以生成具有特定值的指定列的新数据帧。例如。,
import pandas as pd
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split()})
print("Original dataframe:")
print(df)
b_is_two_dataframe = pd.DataFrame(df.groupby('B').get_group('two').reset_index()).drop('index', axis = 1)
#NOTE: the final drop is to remove the extra index column returned by groupby object
print('Sub dataframe where B is two:')
print(b_is_two_dataframe)
运行此命令可以:
Original dataframe:
A B
0 foo one
1 bar one
2 foo two
3 bar three
4 foo two
5 bar two
6 foo one
7 foo three
Sub dataframe where B is two:
A B
0 foo two
1 foo two
2 bar two
使用带有panda>=0.25.00的.query更灵活:
由于panda>=0.25.00,我们可以使用查询方法来使用panda方法过滤数据帧,甚至可以使用带有空格的列名。通常,列名中的空格会给出一个错误,但现在我们可以使用backtick(`)来解决这个问题-请参见GitHub:
# Example dataframe
df = pd.DataFrame({'Sender email':['ex@example.com', "reply@shop.com", "buy@shop.com"]})
Sender email
0 ex@example.com
1 reply@shop.com
2 buy@shop.com
将.query与方法str.endswith一起使用:
df.query('`Sender email`.str.endswith("@shop.com")')
输出
Sender email
1 reply@shop.com
2 buy@shop.com
此外,我们还可以通过在查询中用@前缀来使用局部变量:
domain = 'shop.com'
df.query('`Sender email`.str.endswith(@domain)')
输出
Sender email
1 reply@shop.com
2 buy@shop.com