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

时间:2020-03-31 18:03:01

标签: python python-3.x pandas dataframe

我想获取包含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)

输出:

    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

预期输出:

['comment_2', 'comment_3']

2 个答案:

答案 0 :(得分: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']

答案 1 :(得分:2)

尝试:

['comment_2', 'comment_3']

输出:

strings

它贯穿所有可能为objectres类型)的列,从这些列中删除所有非空格字符,然后仅计算字符。如果所有字符都恰好有2个字符-它将列名添加到{{1}}数组中。