vlookup 相当于使用 pandas 填充现有的 table
vlookup equivalent to fill existing table using pandas
场景:
- python
中有超过三个枢轴table
- 一个现有的table,我想在其中根据不同数据透视表的每行和每列填充值table
我在 excel 做了样品,想在 python 自动化。
(在 python 使用 pivot 进行数据透视列名称更改后)
Pivot1 Pivot2
Name Sum of English Average Name Sum of Maths Average
Ni 7.25 Ni 7.25
Pi 11.25 Pi 11.25
Si 12.25 Si 12.25
Ti 17.25 Ti 17.25
Vi 9.75 Vi 9.75
Grand Total 57.75 Grand Total 57.75
需要table填写
English Avg Maths Avg
Ni ----- ------
Pi ------ ------
Si ------ -------
使用reduce
和pd.merge
:
import pandas as pd
from functools import reduce
names = ['Ni', 'Pi', 'Si']
df = reduce(lambda piv1, piv2: pd.merge(piv1.loc[piv1['Name'].isin(names)],
piv2, on='Name', how='left'),
[pivot1, pivot2, pivot3])
>>> df
Name Sum of English Average Sum of Maths Average Sum of History Average
0 Ni 7.25 7.25 7.25
1 Pi 11.25 11.25 11.25
2 Si 12.25 12.25 12.25
场景:
- python 中有超过三个枢轴table
- 一个现有的table,我想在其中根据不同数据透视表的每行和每列填充值table
我在 excel 做了样品,想在 python 自动化。 (在 python 使用 pivot 进行数据透视列名称更改后)
Pivot1 Pivot2
Name Sum of English Average Name Sum of Maths Average
Ni 7.25 Ni 7.25
Pi 11.25 Pi 11.25
Si 12.25 Si 12.25
Ti 17.25 Ti 17.25
Vi 9.75 Vi 9.75
Grand Total 57.75 Grand Total 57.75
需要table填写
English Avg Maths Avg
Ni ----- ------
Pi ------ ------
Si ------ -------
使用reduce
和pd.merge
:
import pandas as pd
from functools import reduce
names = ['Ni', 'Pi', 'Si']
df = reduce(lambda piv1, piv2: pd.merge(piv1.loc[piv1['Name'].isin(names)],
piv2, on='Name', how='left'),
[pivot1, pivot2, pivot3])
>>> df
Name Sum of English Average Sum of Maths Average Sum of History Average
0 Ni 7.25 7.25 7.25
1 Pi 11.25 11.25 11.25
2 Si 12.25 12.25 12.25