Python 矩阵中的Merg与计算
我在矩阵搜索和计算方面有问题。 我有一个df1,每个指标和国家都有不同的年份值。 我有一个包含国家和年度值组合的df2。 理想的产出是df3,其中每个国家组合都有一个新的列,其中包含创建和计算的指标的乘积 我用loc和Spliting尝试了几件事,但都没有成功 Df1Python 矩阵中的Merg与计算,python,pandas,Python,Pandas,我在矩阵搜索和计算方面有问题。 我有一个df1,每个指标和国家都有不同的年份值。 我有一个包含国家和年度值组合的df2。 理想的产出是df3,其中每个国家组合都有一个新的列,其中包含创建和计算的指标的乘积 我用loc和Spliting尝试了几件事,但都没有成功 Df1 df1 =pd.DataFrame({'Country':['Armenia','Azerbaidjan','Belarus','Armenia','Azerbaidjan','Belarus'],\ '
df1 =pd.DataFrame({'Country':['Armenia','Azerbaidjan','Belarus','Armenia','Azerbaidjan','Belarus'],\
'Indictaor':['G','G','G','H', 'H', 'H'],'2005':[3,4,5,6,7,4],'2006':[6,3,1,3,5,6]})
Df2
Df3
你可以这样做。这只是我认为的众多方式之一
df[df['col']==hoge]
返回匹配的hoge
向dataframe添加带有列表的新列
G = []
H = []
for i in range(4):
rowlist = df2.iloc[i].to_list()
year = str(rowlist[0])
country1 = rowlist[1]
country2 = rowlist[2]
# make G list
tmp1 = df1[df1['Indictaor'] == 'G']
row1 = tmp1[tmp1['Country'] == country1].index[0]
tmp2 = df1[df1['Indictaor'] == 'G']
row2 = tmp2[tmp2['Country'] == country2].index[0]
G.append(df1[year].iloc[row1] * df1[year].iloc[row2])
# make H list
tmp1 = df1[df1['Indictaor'] == 'H']
row1 = tmp1[tmp1['Country'] == country1].index[0]
tmp2 = df1[df1['Indictaor'] == 'H']
row2 = tmp2[tmp2['Country'] == country2].index[0]
H.append(df1[year].iloc[row1] * df1[year].iloc[row2])
df2['IndictaorGProduct'] = G
df2['IndictaorHProduct'] = H
print(df2)
非常感谢shimo的帮助。我几乎把它改编成了我的节目。我遇到的一个问题是,今年的df2是datetime格式的,所以我得到了一个错误。这里有什么帮助吗?我会更改df2时间列的每一项,比如
d=datetime.datetime.now()
pd.to\u datetime(d).strftime(“%Y-%m-%d”)
。使用pd.to_datetime()生成时间戳,使用strftime生成格式化时间。谢谢。在过去的3个小时里,我拼命尝试了所有的方法,但关键的错误都没有改变。他在df1的标题栏中找不到指定的年份。
df3 = pd.DataFrame({'Year':[2005,2006,2005,2006],
'Country2': ['Belarus','Belarus','Belarus','Belarus'],
'Country1':['Armenia','Armenia','Azerbaidjan','Azerbaidjan'],
'IndictaorGProduct':[15,6,35,5],
'IndictaorHProduct':[24,18,28,30]})
G = []
H = []
for i in range(4):
rowlist = df2.iloc[i].to_list()
year = str(rowlist[0])
country1 = rowlist[1]
country2 = rowlist[2]
# make G list
tmp1 = df1[df1['Indictaor'] == 'G']
row1 = tmp1[tmp1['Country'] == country1].index[0]
tmp2 = df1[df1['Indictaor'] == 'G']
row2 = tmp2[tmp2['Country'] == country2].index[0]
G.append(df1[year].iloc[row1] * df1[year].iloc[row2])
# make H list
tmp1 = df1[df1['Indictaor'] == 'H']
row1 = tmp1[tmp1['Country'] == country1].index[0]
tmp2 = df1[df1['Indictaor'] == 'H']
row2 = tmp2[tmp2['Country'] == country2].index[0]
H.append(df1[year].iloc[row1] * df1[year].iloc[row2])
df2['IndictaorGProduct'] = G
df2['IndictaorHProduct'] = H
print(df2)