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

Python中使用.assign()方法结合Lambda报错问题咨询(DataCamp比特币项目)

Fixing .assign() + Lambda Errors in Your Crypto Market Cap DataFrame

Hey there! Let's work through that error you're hitting with the DataCamp "Exploring the Bitcoin Cryptocurrency Market" project, Task 4. First, let's lock in the correct foundation for your cap10 DataFrame, then tackle the .assign() + lambda issue head-on.

Step 1: Correctly Generate cap10

First up, make sure you're creating the top-10 crypto DataFrame properly. The task asks for the top 10 by market cap (not just the first 10 rows), indexed by id. Here's the right code for that:

import pandas as pd

# Critical first step: Convert market_cap_usd to numeric (it's probably stored as strings!)
# The `errors='coerce'` flag turns unconvertible values into NaN (easy to clean later)
cap['market_cap_usd'] = pd.to_numeric(cap['market_cap_usd'], errors='coerce')

# Now create cap10: top 10 by market cap, indexed by their id
cap10 = cap.nlargest(10, 'market_cap_usd').set_index('id')

Skipping the numeric conversion is one of the most common sources of errors here—you can't do arithmetic on string values like '159640995719'.

Step 2: Proper .assign() + Lambda Usage

Assuming the next task step is calculating something like each crypto's share of the total top-10 market cap (a common ask in this project), here's how to use .assign() with lambda correctly:

# Add a new column for market cap percentage using .assign()
cap10 = cap10.assign(
    market_cap_perc=lambda df: (df['market_cap_usd'] / df['market_cap_usd'].sum()) * 100
)

The lambda parameter (df here) refers directly to the cap10 DataFrame, so you can safely access columns through it without referencing the original cap dataset.

Common Error Causes & Fixes

Let's break down why you might be seeing errors:

  • Unconverted string values: If you skip the pd.to_numeric() step, any arithmetic in the lambda will throw a TypeError (you can't divide strings). Fix this with the conversion code above.
  • Incorrect lambda reference: Don't use the original cap DataFrame inside the lambda—always use the lambda parameter (like df) to target the current cap10 dataset. Using cap instead will pull in the full dataset, not just the top 10.
  • Wrong cap10 creation: If you used head(10) instead of nlargest(), you're grabbing the first 10 rows of the dataset, not the top 10 by market cap. This won't throw an error, but it'll give you incorrect results that break downstream steps.

Example Result

After running the code, cap10 will have your top 10 cryptos indexed by their id, plus a new market_cap_perc column showing each coin's share of the total top-10 market cap.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:50:53