Python中转置DataFrame后如何移除索引与列标签以获取目标结果?
Got it, let's work through this to get the exact DataFrame you're aiming for. Here's a step-by-step approach using pandas:
Step 1: Clean up the initial DataFrame
First, your df1 has an empty row (row 3) that we need to remove to avoid extra empty columns in the final result. We'll use dropna() to filter out rows with missing values:
# Clean the df1 by removing rows with empty values df1_clean = df1.dropna()
Step 2: Transpose the cleaned DataFrame
Next, transpose the cleaned DataFrame to swap rows and columns:
df_transposed = df1_clean.T
Step 3: Set the first row as column names
Right now, the transposed DataFrame has filter and filter_value as index labels. We want the values from the filter row to be our new column names:
# Use the first row (filter values) as column headers df_transposed.columns = df_transposed.iloc[0]
Step 4: Remove unwanted rows and labels
Finally, we'll drop the original filter row, reset the index to remove the old index labels, and clear any leftover index name:
# Keep only the filter_value row, drop the old index, and remove index name df_final = df_transposed.iloc[1:].reset_index(drop=True) df_final.index.name = None
After running these steps, your df_final will look exactly like this when printed (you can use print(df_final.to_string(index=False)) to hide the row index entirely):
kol_id thrc_nm jnj_id 101152 VIR 7124166
内容的提问来源于stack exchange,提问作者ashmita

