[英]How do I create a new column based on matching values in two different dataframes?
[英]How do I create multiple dataframes from a loop based on two existing dataframes and matching creteria?
我认为下面的代码可能会使我的问题更容易理解。 但无论如何我都会尝试解释我想要做什么。
我有两个数据框,每个数据框共有一列。 我希望 df2 中基于 df1 的 col 1 中的值匹配的行被放入一个单独的数据帧中并循环遍历 df2 直到我为 df1 的 col1 中的每个条件都有新的数据帧。
Dataframes
df1 = pd.DataFrame([['a', '1'], ['p', '3']],
columns=['col 1', 'col 2'])
df2 = pd.DataFrame([['t','a', '1'], ['q','a', '2'], ['x','p', '3']],
columns=['col 1', 'col 2', 'col 3'])
for strategy in df2:
if df2[df2['col 2']] == df1[df1['col 1']]:
df = df2[df2['col 2']] == df1[df1['strategy']]
df.to_excel("output.xlsx", sheet_name = 'Sheet_name_1')
之后,我想使用循环中的每个新数据框并对其执行一个函数,然后将该新数据框导出到 excel。 但暂时让我们专注于第一个问题。
您的代码示例不清楚输出 Excel 文件中的每个工作表应包含什么内容。
因此,我采用了另一种方法为每个工作表生成 DataFrame:对于df2中col 2列中的每个值(我将其命名为vv ):
要编写包含多个工作表的 Excel 文件,您必须:
执行此操作的代码是:
exw = pd.ExcelWriter('Output.xlsx')
for vv in df2['col 2'].unique():
df1.query('`col 1` == @vv').to_excel(exw, vv)
exw.save()
注意这段代码有多简洁:
现在你必须:
下面是一位同事提供给我的解决方案。 非常感谢他。
因此,我们有两个数据框,在两者(指数和基金)中都有一个共同的列是 Strategy 和 Style。 我们将索引设置为索引数据框中的 Strategy 列值。 然后我们从基金数据框创建一个数据框字典。 其中每一个都基于 Style 值。 现在我们创建一个可以运行的示例函数。 最后,我们创建了一个函数,该函数选择每个新数据帧并获取分配给每个基金的索引并将它们传递给我们的新函数,并为我们提供最终的数据帧集。 在这一点上,我们将每个工作表单独导出到 excel(我仍在研究这部分)
import pandas as pd
indices = pd.DataFrame([['Volatility', 'SPX Index'], ['Multistrategy', 'SXXP Index'], ['Real Estate', 'IBEX Index']],
columns=['Strategy', 'Ticker'])
indices = indices.set_index('Strategy') # i would have the strategy as index to help with mapping later
funds = pd.DataFrame([['MABAX US Equity','Real Estate', 'name1'], ['SPY US Equity','Real Estate', 'name2'],
['AAPL US Equity','Volatility', 'name3']],
columns=['Ticker', 'Style', 'Name'])
strategies = indices.index.values
data_frames = {strategy:funds[funds['Style']==strategy] for strategy in strategies}
#this gives you a dictionary of dataframes so you can get funds of volatility with
# something like: data_frames['Volatility']
def my_function(fund_df,parameter,index_ticker):
#this is your function and it takes the fund df of each
#strategy and also the index ticker of each strategy
print(fund_df)
print(index_ticker)
return
#you could run the function for each dataframe and each index by using something like:
for strategy in strategies:
index_ticker = indices.loc[strategy,'Ticker']
fund_df = data_frames[strategy]
my_function(fund_df,'M',index_ticker)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.