熊猫获取列包含所有行中的字符

som*_*mal 2 python dataframe python-3.x pandas

我想获取包含所有带有 2 个空格的行的数据框列的列表。

输入:

import pandas as pd
import numpy as np
pd.options.display.max_columns = None
pd.options.display.max_rows = None
pd.options.display.expand_frame_repr = False

df = pd.DataFrame({'id': [101, 102, 103],
                   'full_name': ['John Brown', 'Bob Smith', 'Michael Smith'],
                   'comment_1': ['one two', 'qw er ty', 'one space'],
                   'comment_2': ['ab xfd xsxws', 'dsd sdd dwde', 'wdwd ofjpoej oihoe'],
                   'comment_3': ['ckdf cenfw cd', 'cewfwf wefep lwcpem', np.nan],
                   'birth_year': [1960, 1970, 1970]})

print(df)
Run Code Online (Sandbox Code Playgroud)

输出:

    id      full_name  comment_1           comment_2            comment_3  birth_year
0  101     John Brown    one two        ab xfd xsxws        ckdf cenfw cd        1960
1  102      Bob Smith   qw er ty        dsd sdd dwde  cewfwf wefep lwcpem        1970
2  103  Michael Smith  one space  wdwd ofjpoej oihoe                  NaN        1970
Run Code Online (Sandbox Code Playgroud)

预期输出:

['comment_2', 'comment_3']
Run Code Online (Sandbox Code Playgroud)

G. *_*son 7

您可以使用series.str.count()来计算字符串中子字符串或模式的出现次数,用于.all()检查所有项目是否符合条件,并df.columns仅使用字符串列进行迭代select_dtypes('object')

[i for i in df.select_dtypes('object').columns if (df[i].dropna().str.count(' ')==2).all()]    
['comment_2', 'comment_3']
Run Code Online (Sandbox Code Playgroud)