【问题标题】:Find column whose name contains a specific value that is in a fixed column查找名称包含固定列中特定值的列
【发布时间】:2020-08-30 17:39:47
【问题描述】:

我有一个带有列名的数据框,我想找到包含某个值的数据框。我正在像“...._segment”这样的列名中搜索“segment”列中的值。 我希望将列名作为字符串或变量返回,因此稍后我可以正常使用 df['name'] 或 df[name] 访问该列。 enter image description here

【问题讨论】:

  • 你能告诉我们你到目前为止尝试了什么吗?
  • 我只能搜索一个固定的字符串。例如: selected_cols =[x for x in df.columns[df.columns.str.contains('402')]]
  • 请分享您的代码。这里有一些说明。请注意“无屏幕截图”警告。 stackoverflow.com/help/how-to-ask

标签: python pandas


【解决方案1】:

我不知道你是想获取包含你想要的字符串的列名,还是至少有一个值包含你想要的字符串的列的列名。

如果数据框是:

In [1]: import pandas as pd 
   ...: df = pd.DataFrame({'a_1': ['b_1', 'b_2'], 'b_1': ['a_1', 'a_2']})                                                                             
In [2]: df                                                                                                                                            
Out[2]: 
   a_1  b_1
0  b_1  a_1
1  b_2  a_2

对于第一种情况,如果要查找与a_*匹配的所有列名:

In [3]: import re                                                                                                                                     
In [4]: columns = [col for col in df.columns if isinstance(col, str) and re.match('a_.*', col)]                                                       
In [5]: columns                                                                                                                                       
Out[5]: ['a_1']

对于第二种情况,如果要查找至少有一个值与a_.* 匹配的所有列:

In [6]: columns = [col for col, ser in df.iteritems() if ser.str.match('a_.*').any()]                                                                 
In [7]: columns                                                                                                                                       
Out[7]: ['b_1']

其中:

df.iteritems:返回(列名,列值(系列))对的迭代器。

Series.any:如果系列中的任何值为True,则返回True

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2020-06-01
    • 2013-12-20
    相关资源
    最近更新 更多