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

时间:2019-03-29 06:19:03

标签: python pandas

说我有一个像这样的表:

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

4 个答案:

答案 0 :(得分:1)

  

我只想加载包含以右括号[

开头的值的列

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

[08001][unixODBC][Teradata][ODBC] (10380) Unable to establish connection with data source. Missing settings: {[DBCName]}

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

请注意,startswith和contains之间是有区别的。这些文档是说明性的。

答案 1 :(得分:0)

您可以尝试以下方法吗?

>>> 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
>>>

答案 2 :(得分:0)

使用此:

s=df.applymap(lambda x: '[' in x).any()
print(df[s[s].index])

输出:

  col2 col4
0    b   [d
1   [f    h
2    j    l
3    n  [pa

答案 3 :(得分:0)

请尝试一下,希望它对您有用

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