【发布时间】:2018-09-05 20:28:15
【问题描述】:
我有两个数据框 df1 和 df2,并希望根据其中一列中的值将它们合并到 df3,如下所示。
请问,我该怎么做?
df1:
+---+----+
| | b |
+---+----+
| 1 | 3 |
| 2 | 4 |
| 3 | 7 |
| 4 | 8 |
| 5 | 10 |
+---+----+
df2:
+---+-------+-----+
| | x | y |
+---+-------+-----+
| 3 | True | 5.4 |
| 3 | False | 6.9 |
| 4 | True | 9.8 |
| 7 | True | 7.8 |
| 8 | False | 5.6 |
+---+-------+-----+
df3:
+---+---+--------+-----+
| | b | y_notx | y_x |
+---+---+--------+-----+
| 1 | 3 | 6.9 | 5.4 |
| 2 | 4 | NaN | 9.8 |
| 3 | 7 | NaN | 7.8 |
| 4 | 8 | 5.6 | NaN |
+---+---+--------+-----+
代码:
import pandas as pd
t1 = {'b': [3, 4, 7, 8, 10]}
df1 = pd.DataFrame(t1, index=[1,2,3,4,5])
t2 = {'x' : [True, False, True, True, False],
'y' : [5.4,6.9,9.8,7.8,5.6]}
df2 = pd.DataFrame(t2, index=[3,3,4,7,8])
t3 = {'b': [3, 4, 7, 8],
'y_x': [5.4, 9.8, 7.8, pd.np.nan],
'y_notx': [6.9, pd.np.nan, pd.np.nan, 5.6]}
df3 = pd.DataFrame(t3, index=[1, 2, 3, 4])
【问题讨论】:
-
您能否详细解释一下用于获取
df3的操作?术语b确定在df2下查找哪个索引,并返回y_x下的x True 术语和y_notx下的x False 术语。而b列由df1确定?对吗? -
是的,没错! :-)
-
非常有趣的问题,感谢发帖。