gpt4 book ai didi

python - 为值表中的观察值赋值

转载 作者:行者123 更新时间:2023-11-28 21:50:53 25 4
gpt4 key购买 nike

我有一个大型的观察 DataFrame。即

value 1,value 2
a,1
a,1
a,2
b,3
a,3

我现在有一个值的外部 DataFrame

_  ,a,b
1 ,10,20
2 ,30,40
3 ,50,60

将索引表中的值添加到第一个 DataFrame 的有效方法是什么?即:

value 1,value 2, new value
a,1,10
a,1,10
a,2,30
b,3,60
a,3,50

最佳答案

使用 .lookup() 的替代解决方案。它只是一行,矢量化的解决方案。适用于大型数据集。

import pandas as pd
import numpy as np

# generate some artificial data
# ================================
np.random.seed(0)
df1 = pd.DataFrame(dict(value1=np.random.choice('a b'.split(), 10), value2=np.random.randint(1, 10, 10)))

df2 = pd.DataFrame(dict(a=np.random.randn(10), b=np.random.randn(10)), columns=['a', 'b'], index=np.arange(1, 11))

df1

Out[178]:
value1 value2
0 a 6
1 b 3
2 b 5
3 a 8
4 b 7
5 b 9
6 b 9
7 b 2
8 b 7
9 b 8


df2

Out[179]:
a b
1 2.5452 0.0334
2 1.0808 0.6806
3 0.4843 -1.5635
4 0.5791 -0.5667
5 -0.1816 -0.2421
6 1.4102 1.5144
7 -0.3745 -0.3331
8 0.2752 0.0474
9 -0.9608 1.4627
10 0.3769 1.5350



# processing: one liner lookup function
# =======================================================
# df1.value2 is the index and df1.value1 is the column
df1['new_values'] = df2.lookup(df1.value2, df1.value1)

Out[181]:
value1 value2 new_values
0 a 6 1.4102
1 b 3 -1.5635
2 b 5 -0.2421
3 a 8 0.2752
4 b 7 -0.3331
5 b 9 1.4627
6 b 9 1.4627
7 b 2 0.6806
8 b 7 -0.3331
9 b 8 0.0474

关于python - 为值表中的观察值赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31341039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com