如何用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 usingisinstance()—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_columnslist.
If you want to extract just those columns from your DataFrame, you can do:
filtered_df = df[matching_columns]
内容的提问来源于stack exchange,提问作者alex
相关产品推荐
相关产品推荐

