我有2个dataframes,我想借此一列从一个和多个基于价值观的第二创建新列(其他)列大熊猫 - 多列
第一数据框(合并dataframes有条件df1
):
df1 = pd.DataFrame({'cond': np.repeat([1,2], 5),
'point': np.tile(np.arange(1,6), 2),
'value1': np.random.rand(10),
'unused1': np.random.rand(10)})
cond point unused1 value1
0 1 1 0.923699 0.103046
1 1 2 0.046528 0.188408
2 1 3 0.677052 0.481349
3 1 4 0.464000 0.807454
4 1 5 0.180575 0.962032
5 2 1 0.941624 0.437961
6 2 2 0.489738 0.026166
7 2 3 0.739453 0.109630
8 2 4 0.338997 0.415101
9 2 5 0.310235 0.660748
和第二(df2
):
df2 = pd.DataFrame({'cond': np.repeat([1,2], 10),
'point': np.tile(np.arange(1,6), 4),
'value2': np.random.rand(20)})
cond point value2
0 1 1 0.990252
1 1 2 0.534813
2 1 3 0.407325
3 1 4 0.969288
4 1 5 0.085832
5 1 1 0.922026
6 1 2 0.567615
7 1 3 0.174402
8 1 4 0.469556
9 1 5 0.511182
10 2 1 0.219902
11 2 2 0.761498
12 2 3 0.406981
13 2 4 0.551322
14 2 5 0.727761
15 2 1 0.075048
16 2 2 0.159903
17 2 3 0.726013
18 2 4 0.848213
19 2 5 0.284404
df1['value1']
包含EAC值h组合cond
和point
。
我想在df2
包含来自df1['value1']
值来创建一个新的列(new_column
),但值应该在哪里cond
和point
跨过2个dataframes匹配的人。
所以我期望的输出是这样的:
cond point value2 new_column
0 1 1 0.990252 0.103046
1 1 2 0.534813 0.188408
2 1 3 0.407325 0.481349
3 1 4 0.969288 0.807454
4 1 5 0.085832 0.962032
5 1 1 0.922026 0.103046
6 1 2 0.567615 0.188408
7 1 3 0.174402 0.481349
8 1 4 0.469556 0.807454
9 1 5 0.511182 0.962032
10 2 1 0.219902 0.437961
11 2 2 0.761498 0.026166
12 2 3 0.406981 0.109630
13 2 4 0.551322 0.415101
14 2 5 0.727761 0.660748
15 2 1 0.075048 0.437961
16 2 2 0.159903 0.026166
17 2 3 0.726013 0.109630
18 2 4 0.848213 0.415101
19 2 5 0.284404 0.660748
在这个例子中,我可以只使用瓦/重复,但在现实中df1['value1']
不适合这么整齐地进入其他数据帧。所以,我只是需要做的是基于匹配的cond
和point
列
我已经试过将它们合并,但1)数字不似乎匹配和2)我不想从df1
带过来的任何未使用的列:
df1.merge(df2, left_on=['cond', 'point'], right_on=['cond', 'point'])
请告诉我正确的方式,而不必通过2个dataframes迭代添加这个新列?
由于@jezrael。你也是。 – piRSquared