Pandas DataFrame单行单值选取:如何提取指定列每行的第二个元素
Got it, let's work through this step by step. First, I notice your column A has comma-separated strings (like "3, 2, 1") instead of actual lists, so we need to split those strings into usable lists first before grabbing the second element.
Here's how to get your desired output:
First, let's recreate your sample DataFrame to test with:
import pandas as pd # Your sample data df = pd.DataFrame({ 'A': ['3, 2, 1', '3, 2, 1', '3, 2, 1'], 'B': ['5, 6, 7', '5, 6, 7', '5, 6, 7'] })
Step-by-step solution
Split strings into lists
Use Pandas' vectorizedstr.split()method to turn each string in column A into a list of elements. We split on', '(comma + space) to avoid extra whitespace in the resulting elements:df['A_split'] = df['A'].str.split(', ')This creates a new column where each entry is a list like
['3', '2', '1'].Grab the second element
Since Python uses 0-indexing, the second element is at position 1. Usestr[1]to access this element from every list in the column:second_values = df['A_split'].str[1]This gives a Series with values
['2', '2', '2'].Convert to integer tuple
To get the integer tuple you want, convert the Series values to integers then wrap them in a tuple:result = tuple(second_values.astype(int))
One-line shortcut
You can combine all steps into a single line without creating intermediate columns:
result = tuple(df['A'].str.split(', ').str[1].astype(int))
Output
When you run this, you'll get exactly your expected result:
print(result) # Output: (2, 2, 2)
Alternative (less efficient for large data)
If you prefer using apply with a lambda, this works too—though note vectorized string methods are faster for big datasets:
result = tuple(df['A'].apply(lambda x: int(x.split(', ')[1])))
That's all! This should give you the tuple of second values from column A that you need.
内容的提问来源于stack exchange,提问作者TimNeedsHalp

