如何使数据帧列在使用它作为pi与另一列合并时保持不变

2024-09-30 18:24:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望df1中的col1在与df2合并后保留三个“a”,并将其余列中的所有信息带到新的数据帧中

要显示问题,请执行以下操作:

dt1 = pd.DataFrame({"col1": ["a","a", "a", "b", "c"], "col2": ["whatever", "whatever1", "whatever2", "whatever3", "whatever4"] })
dt2 = pd.DataFrame({"col1": ["a","a", "a", "b", "c"], "col3": ["w", "1", "w2", "w3", "w4"]})
dt3 = dt1.merge(dt2, on = "col1", how = "left")

我不喜欢的结果是

col1  col2  col3

col       col2     col3
a       whatever        w
a       whatever        1
a       whatever        w2
a       whatever1       w
a       whatever1       1
a       whatever1       w2
a       whatever2       w
a       whatever2       1
a       whatever2       w2
b       whatever3       w3
c       whatever4       w4

我正在搜索的结果是:

col1     col2      col3
 a      whatever    w
 a      whatever1   1
 a      whatever2   w2
 b      whatever3   w3
 c      whatever4   w4

Tags: dataframecol2col3col1pdwhateverw3w2