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

Pandas操作:删除列层级并仅保留City与geometry列

Solution for Multi-Level Column Pandas DataFrame Cleanup

Got it, let's walk through this problem step by step. You have a Pandas DataFrame with multi-level columns, including fields like AREA, AA5000, City, and geometry, and you need to strip one column level while keeping only the City and geometry columns. Here's how to do it smoothly:

Step 1: Filter the Columns You Need First

Start by narrowing down your DataFrame to only the columns you care about—this avoids unnecessary processing on other columns:

# Keep only City and geometry columns (adjust syntax if your multi-level columns use tuples)
filtered_df = df.loc[:, ['City', 'geometry']]

Note: If your multi-level columns are structured with explicit level groups (e.g., ('Metadata', 'City')), you can filter using tuples like filtered_df = df.loc[:, [('Location', 'City'), ('Spatial', 'geometry')]].

Step 2: Remove the Extra Column Level

Once you have your filtered subset, drop the unwanted column level using droplevel(). The parameter you pass depends on which level you want to remove (0 for the first level, 1 for the second, etc.):

# Drop the first column level (adjust the number to match your actual structure)
filtered_df.columns = filtered_df.columns.droplevel(0)

# Alternatively, explicitly keep the second level's names if needed:
# filtered_df.columns = filtered_df.columns.get_level_values(1)

Quick Example for Context

Suppose your original DataFrame has a column MultiIndex like this:

MultiIndex([('Metrics', 'AREA'),
            ('Metrics', 'AA5000'),
            ('Location', 'City'),
            ('Location', 'geometry')],
           names=['Category', 'Field'])

After running the code above, your filtered_df will have flat columns: ['City', 'geometry'], with all rows (including Detroit and Austin) preserved along with their POLYGON geometry data.

Pro Tip

If you're unsure which level to drop, check your column structure first with:

print(df.columns)
# Or view the distinct level values with:
print(df.columns.levels)

内容的提问来源于stack exchange,提问作者Calculus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:50:23