如何将DataFrame指定列转为Numpy数组并按列循环遍历
Got it, let's fix this step by step. Here's how you can extract only columns A, B, C into a NumPy array and loop through them in order:
Step 1: Extract Specific Columns to NumPy Array
Instead of converting the entire DataFrame, first select the columns you need. Also, note that as_matrix() is deprecated in newer Pandas versions—use to_numpy() for better compatibility:
import pandas as pd df = pd.DataFrame([ ['2018-02-01', 1, 3, 6, 102, 8], ['2018-02-01', 2, 3, 4, 5, 6], ['2018-02-02', 6, 7, 8, 4, 2], ['2018-02-03', 3, 4, 5, 6, 7] ], columns=['A', 'B', 'C', 'D', 'E', 'F']) # Extract only A, B, C columns and convert to NumPy array nparray = df[['A', 'B', 'C']].to_numpy() print("NumPy array with A,B,C columns:\n", nparray)
Step 2: Loop Through Columns in Order
There are two clean ways to iterate through the columns (A first, then B, then C):
Option 1: Iterate by Column Index
Use the array's shape to get the number of columns, then loop through each index to slice the column:
print("\nLooping through columns by index:") for col_idx in range(nparray.shape[1]): column = nparray[:, col_idx] print(f"Column {col_idx + 1} (original column {['A','B','C'][col_idx]}):", column)
Option 2: Transpose the Array and Iterate
Transposing swaps rows and columns, so each row in the transposed array is an original column. This is often more readable when you want to pair columns with their names:
print("\nLooping through columns via transpose:") for col_name, column in zip(['A','B','C'], nparray.T): print(f"Column {col_name}:", column)
Output Explanation
Running this code will first print the NumPy array containing only your target columns. Then it will loop through each column in sequence, printing the values along with the original column name for clarity.
内容的提问来源于stack exchange,提问作者MCM

