Alb*_*ino 1 python dataframe pandas
我需要限制数据集,以便它仅返回包含特定字符串的行,但是,该字符串可以存在于许多 (8) 列中。
我怎样才能做到这一点?我见过 str.isin 方法,但它返回单行的单个系列。如何删除任何列中包含该字符串的任何行。
示例代码如果我有由生成的数据帧 df
import pandas as pd
data = {'year': [2011, 2012, 2013, 2014, 2014, 2011, 2012, 2015],
'year2': [2012, 2016, 2015, 2015, 2012, 2013, 2019, 2016],
'reports': [52, 20, 43, 33, 41, 11, 43, 72]}
df = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
df
year year2 reports
a 2011 2012 52
b 2012 2016 20
c 2013 2015 43
d 2014 2015 33
e 2014 2012 41
f 2011 2013 11
g 2012 2019 43
h 2015 2016 72
Run Code Online (Sandbox Code Playgroud)
我希望代码删除不包含值 2012 的所有行。请注意,在我的实际数据集中,它是一个字符串,而不是一个 int (它是人名),因此在上面的代码中它将删除行c, d, f, and h.
df[df.eq('2012').any(1)] #for year as string
Run Code Online (Sandbox Code Playgroud)
或者:
df[df.eq(2012).any(1)] #for year as int
Run Code Online (Sandbox Code Playgroud)
year year2 reports
a 2011 2012 52
b 2012 2016 20
e 2014 2012 41
g 2012 2019 43
Run Code Online (Sandbox Code Playgroud)