Tan*_*nya 6 python dataframe pandas
我正在尝试从数据集中删除一组列.要删除的所有变量都以文本"prefix"结尾.
然后尝试了一系列方法来删除导致各种错误的组.任何人都可以,提出一种方法来删除这些列?
df2 = df.drop([col for col in df.columns if 'prefix' in col],axis=1)
Run Code Online (Sandbox Code Playgroud)
使用filter和regex
df.filter(regex=r'^((?!prefix).)*$')
Run Code Online (Sandbox Code Playgroud)
df = pd.DataFrame(np.random.rand(2, 6),
columns=['oneprefix', 'one',
'twoprefix', 'two',
'threeprefix', 'three'])
df.filter(regex=r'^((?!prefix).)*$')
Run Code Online (Sandbox Code Playgroud)
哪里:
df
Run Code Online (Sandbox Code Playgroud)
为了完整起见:
In [306]: df
Out[306]:
prefixcol1 col2prefix col3prefix colN
0 1 1 1 1
1 2 2 2 2
2 3 3 3 3
In [307]: df.loc[:, ~df.columns.str.contains('prefix$')]
Out[307]:
prefixcol1 colN
0 1 1
1 2 2
2 3 3
Run Code Online (Sandbox Code Playgroud)
或另一种变体:
In [388]: df.select(lambda x: re.search(r'prefix$', str(x)) is None, axis=1)
Out[388]:
prefixcol1 colN
0 1 1
1 2 2
2 3 3
Run Code Online (Sandbox Code Playgroud)