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

Python中转置DataFrame后如何移除索引与列标签以获取目标结果?

Solution for Transposing DataFrame and Removing Labels

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 07:02:37