[英]Python Pandas: How to map values from a dictionary of dataframes based on column values in main frame?
I am trying to create a column in my main dataframe DF_MAIN by mapping over values from another dataframe that is part of a larger dictionary of dataframes DF_DICTDF.我试图通过映射来自另一个数据帧的值来在我的主数据帧 DF_MAIN 中创建一列,该数据帧是更大的数据帧 DF_DICTDF 字典的一部分。 The dataframe from which to map in DF_DICTDF depends on the value in a column in DF_MAIN.
在 DF_DICTDF 中映射的数据帧取决于 DF_MAIN 中列中的值。
For greater detail, I am creating a "RATE" column in the main dataframe and each dataframe in the dictionary corresponds to a table of currency exchange rates for each month.更详细地说,我在主数据框中创建了一个“RATE”列,字典中的每个数据框对应于每个月的货币汇率表。 The rates need to be mapped over based on a "CURRENCY" column in DF_MAIN.
需要根据 DF_MAIN 中的“CURRENCY”列映射汇率。 The dictionary has a naming convention as follows: 2018January, 2018February, 2018March... which correspond to values in the "YEARMONTH" column of DF_MAIN.
字典的命名约定如下:2018January、2018February、2018March...对应于DF_MAIN的“YEARMONTH”列中的值。
DF_MAIN is one dataframe that contains columns "NAMES", "PRICES", "CURRENCIES" (ie CNY, USD, JPY, EUR...) and "YEARMONTH" (ie 2018January, 2018February...). DF_MAIN 是一个包含列“NAMES”、“PRICES”、“CURRENCIES”(即 CNY、USD、JPY、EUR...)和“YEARMONTH”(即 2018January、2018February...)的数据框。
DF_DICTDF is a dictionary of dataframes. DF_DICTDF 是一个数据框字典。 The names of the dataframes within this dictionary are simply YEARMONTH (ie 2018January, etc.) so that each dataframe contains currency cross rates corresponding to that month.
此字典中数据框的名称只是 YEARMONTH(即 2018January 等),因此每个数据框都包含与该月对应的货币交叉汇率。 The column and row index for each YEARMONTH dataframe is simply currency symbols (ie CNY, USD, JPY, EUR, etc.).
每个 YEARMONTH 数据框的列和行索引只是货币符号(即 CNY、USD、JPY、EUR 等)。
I tried to apply the following:我尝试应用以下内容:
DF_MAIN['RATE']=DF_MAIN['CURRENCY'].map(DF_DICTDF[DF_MAIN['YEARMONTH']].set_index('CURRENCY')['EUR'].to_dict())
When I try to run this, I get the following error:当我尝试运行它时,出现以下错误:
TypeError: 'Series' objects are mutable, thus they cannot be hashed
Same as above but breaking it out into two steps for clarity:与上面相同,但为了清楚起见,将其分为两个步骤:
### Create dictionary of cross rates to map
crossrates=DF_DICTDF[DF_MAIN['YEARMONTH']].set_index('CURRENCY')['EUR'].to_dict()
### Final Mapping of Values:
DF_MAIN['RATE']=DF_MAIN['CURRENCY'].map(crossrates)
All help appreciated.所有帮助表示赞赏。 If this is a duplicate please provide a link.
如果这是重复的,请提供链接。
I was able to make it work using the following:我能够使用以下方法使其工作:
def convert(row):
x='EUR'
y=row['CURRENCY']
z=row['YEARMONTH']
return DF_DICTDF[z].set_index('CURRENCY').loc[x,y]
DF_MAIN['RATE']=DF_MAIN.apply(lambda row: convert(row),axis=1)
(Will edit at a later time to elaborate). (稍后将编辑以详细说明)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.