You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Pandas获取首元素含'|'的DataFrame列

Solution

To find columns where the first element contains a |, you can use a list comprehension that checks each column's initial value:

import pandas as pd

# Your sample DataFrame
df = pd.DataFrame({'A': ['ex1|context1', 1, 'ex3|context3', 3], 'B': [5, 'ex2|context2', 6, 'data']})

# Get columns where first element is a string containing '|'
matching_columns = [col for col in df.columns 
                    if isinstance(df[col].iloc[0], str) and '|' in df[col].iloc[0]]

print(matching_columns)  # Output: ['A']

Explanation:

  • Iterate over columns: We loop through each column name in df.columns.
  • Check element type: First, we verify the first element (df[col].iloc[0]) is a string using isinstance()—this prevents errors when checking for | in non-string values (like integers in your sample).
  • Check for pipe character: If the element is a string, we then check if '|' is present in it.
  • Collect results: Columns that meet both conditions are added to the matching_columns list.

If you want to extract just those columns from your DataFrame, you can do:

filtered_df = df[matching_columns]

内容的提问来源于stack exchange,提问作者alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:43:03