为了账号安全,请及时绑定邮箱和手机立即绑定

在 Python 中,如何读取值以某个字符串开头的所有列?

在 Python 中,如何读取值以某个字符串开头的所有列?

慕村225694 2021-12-21 16:09:02
假设我有一张像:col1    col2    col3    col4a       b       c       [de       [f      g       hi       j       k       lm       n       o       [p我只想加载包含以左括号开头的值的列 [。所以我希望以下内容作为数据帧返回col 2    col4b        [d[f       hj        ln        [p
查看完整描述

3 回答

?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

我只想加载包含以右括号 [ 开头的值的列


为此,您需要 series.str.startswith():


df.loc[:,df.apply(lambda x: x.str.startswith('[')).any()]

  col2 col4

0    b   [d

1   [f    h

2    j    l

3    n   [p

请注意,startswith 和contains 之间存在差异。文档是解释性的。


查看完整回答
反对 回复 2021-12-21
?
慕少森

TA贡献2019条经验 获得超9个赞

您可以尝试以下操作:


>>> df = pd.DataFrame([[1, 2, 4], [4, 5, 6], [7, '[8', 9]])

>>> df = df.astype('str')

>>> df

   0   1  2

0  1   2  4

1  4   5  6

2  7  [8  9

>>> df[df.columns[[df[i].str.contains('[', regex=False).any() for i in df.columns]]]

    1

0   2

1   5

2  [8

>>>


查看完整回答
反对 回复 2021-12-21
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

请试试这个,希望这对你有用


df = pd.DataFrame([['a', 'b', 'c','[d'], ['e','[f','g','h'],['i','j','k','l'],['m','n','o','[p']],columns=['col1','col2','col3','col4'])

cols = []

for col in df.columns:

    if df[col].str.contains('[',regex=False).any() == True:

        cols.append(col)


df[cols]

输出


    col2    col4

0   b   [d

1   [f  h

2   j   l

3   n   [p


查看完整回答
反对 回复 2021-12-21
  • 3 回答
  • 0 关注
  • 344 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号