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

假设我有一张像:


col1    col2    col3    col4

a       b       c       [d

e       [f      g       h

i       j       k       l

m       n       o       [p

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


所以我希望以下内容作为数据帧返回


col 2    col4

b        [d

[f       h

j        l

n        [p


慕村225694
浏览 345回答 3
3回答

摇曳的蔷薇

我只想加载包含以右括号 [ 开头的值的列为此,您需要 series.str.startswith():df.loc[:,df.apply(lambda x: x.str.startswith('[')).any()]  col2 col40    b   [d1   [f    h2    j    l3    n   [p请注意,startswith 和contains 之间存在差异。文档是解释性的。

慕少森

您可以尝试以下操作:>>> df = pd.DataFrame([[1, 2, 4], [4, 5, 6], [7, '[8', 9]])>>> df = df.astype('str')>>> df   0   1  20  1   2  41  4   5  62  7  [8  9>>> df[df.columns[[df[i].str.contains('[', regex=False).any() for i in df.columns]]]    10   21   52  [8>>>

慕码人2483693

请试试这个,希望这对你有用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    col40   b   [d1   [f  h2   j   l3   n   [p
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python