Python中使用.assign()方法结合Lambda报错问题咨询(DataCamp比特币项目)
.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 aTypeError(you can't divide strings). Fix this with the conversion code above. - Incorrect lambda reference: Don't use the original
capDataFrame inside the lambda—always use the lambda parameter (likedf) to target the currentcap10dataset. Usingcapinstead will pull in the full dataset, not just the top 10. - Wrong
cap10creation: If you usedhead(10)instead ofnlargest(), 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

