gpt4 book ai didi

python - Pandas 获取列包含所有行中的字符

转载 作者:行者123 更新时间:2023-12-02 06:29:32 30 4
gpt4 key购买 nike

我想获取包含所有带 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']

最佳答案

您可以使用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']

关于python - Pandas 获取列包含所有行中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60957046/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com