在 python 中使用 .assign() 方法和 lambda
Posted
技术标签:
【中文标题】在 python 中使用 .assign() 方法和 lambda【英文标题】:use .assign() method with lambda in python 【发布时间】:2018-08-19 02:20:20 【问题描述】:我在 Python 中运行这段代码:
#Declaring these now for later use in the plots
TOP_CAP_TITLE = 'Top 10 market capitalization'
TOP_CAP_YLABEL = '% of total cap'
# Selecting the first 10 rows and setting the index
cap10 = cap.loc[:10, :].set_index('id')
# Calculating market_cap_perc
cap10 = cap10.assign(market_cap_perc =
lambda x: (x.market_cap_usd / cap.market_cap_usd.sum()) * 100)
# Plotting the barplot with the title defined above
ax = cap10.plot.bar(x= id, y= market_cap_perc)
ax.set_title(TOP_CAP_TITLE)
# Annotating the y axis with the label defined above
ax.set_ylabel(TOP_CAP_YLABEL)
得到一个错误:
NameError Traceback (most recent call last) in ()
10 lambda x: (x.market_cap_usd / cap.market_cap_usd.sum()) * 100)
11 # Plotting the barplot with the title defined above --->
12 ax = cap10.plot.bar(x= id, y= market_cap_perc)
13 ax.set_title(TOP_CAP_TITLE)
14 # Annotating the y axis with the label defined above
NameError: name 'market_cap_perc' is not defined
这是来自探索比特币加密货币市场的 DataCamp 项目的 Task4 的代码。 cap
是带有id
列的DataFrame(例如'bitcoin'、'ripple')。另一列market_cap_usd
(此列包含以美元为单位的加密货币市场的成本。例如,“159640995719”-market_cap_usd
表示比特币)。
有完成此任务的说明:
1.选择前10个硬币,将索引设置为id
,并将生成的DataFrame分配给cap10
。
2.使用assign()
计算每个硬币的市值百分比,并再次将其分配给cap10
。
3.在标题为“Top 10 market capitalization”的条形图中绘制前 10 个硬币的market_cap_perc
,并将其分配给ax
。
4.使用ax
对象,在y轴上标注“% of total cap”。
我尝试在 lambda 之前定义 market_cap_perc:
market_cap_perc = 0
并得到一个错误:
KeyError Traceback (most recent call last)
2133 try:
-> 2134 return self._engine.get_loc(key)
2135 except KeyError:
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4443)()
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4289)()
KeyError: 139887424317984
【问题讨论】:
导致问题的不是 lambda,而是更下方的ax = cap10.plot.bar(x= id, y= market_cap_perc)
行。回溯部分中间中的行。
您在代码中没有设置名称 market_cap_perc
,因此您也无法将其传递给该调用。
看起来您未能在代码的其他地方定义market_cap_perc
【参考方案1】:
我得到了答案:
import pandas as pd
# Reading datasets/coinmarketcap_06122017.csv into pandas
dec6 = pd.read_csv('datasets/coinmarketcap_06122017.csv')
# Selecting the 'id' and the 'market_cap_usd' columns
market_cap_raw = dec6[['id','market_cap_usd']]
cap = market_cap_raw.query('market_cap_usd > 0')
#Declaring these now for later use in the plots
TOP_CAP_TITLE = 'Top 10 market capitalization'
TOP_CAP_YLABEL = '% of total cap'
# Selecting the first 10 rows and setting the index
cap10 = cap.head(10).set_index('id')
# Calculating market_cap_perc
cap10 = cap10.assign(market_cap_perc = lambda x: (x.market_cap_usd/cap.market_cap_usd.sum())*100)
# Plotting the barplot with the title defined above
ax = cap10.market_cap_perc.head(10).plot.bar(title=TOP_CAP_TITLE)
# Annotating the y axis with the label defined above
ax.set_ylabel(TOP_CAP_YLABEL)
【讨论】:
以上是关于在 python 中使用 .assign() 方法和 lambda的主要内容,如果未能解决你的问题,请参考以下文章
python tensorflow.assign赋值操作方法