【发布时间】:2015-06-12 04:09:00
【问题描述】:
我有一个系列,我将其分为两部分,因为这些部分包含需要以不同方式处理的术语。之后,我想按照原来的顺序合并这两个拆分系列(实际上,在处理之后,它们现在是两列数据帧)。我几乎解决了它:
import pandas as pd
terms = pd.Series(["oo1", "oo2", "oo3", "aa1", "aa2", "oo4"], name="term")
# 0 oo1
# 1 oo2
# 2 oo3
# 3 aa1
# 4 aa2
# 5 oo4
terms_oo = terms[terms.apply(lambda term: "oo" in term)]
# 0 oo1
# 1 oo2
# 2 oo3
# 5 oo4
terms_aa = terms[terms.apply(lambda term: "aa" in term)]
# 3 aa1
# 4 aa2
# process differently so you end up with
df_aa = pd.concat([terms_aa, pd.Series(["taa1", "taa2"], index=[3, 4])], axis=1)
df_aa.columns = ["term", "annotations"]
# term annotations
# 3 aa1 taa1
# 4 aa2 taa2
df_oo = pd.concat([terms_oo, pd.Series(["too1", "too2", "too3", "too4"], index=[0, 1, 2, 5])], axis=1)
df_oo.columns = ["term", "annotations"]
# term annotations
# 0 oo1 too1
# 1 oo2 too2
# 2 oo3 too3
# 5 oo4 too4
现在我想组合 df_aa 和 df_oo 以便它们具有 terms 中的原始顺序,并且 annotations 是一列,包括来自 df_aa 和 df_oo 的值。我该怎么做?
我尝试了以下方法,但找不到所需的最后一步:
terms_df = pd.DataFrame(terms)
m1 = terms_df.merge(df_aa, on="term", how="outer")
m2 = m1.merge(df_oo, on="term", how="outer")
# term annotations_x annotations_y
# 0 oo1 NaN too1
# 1 oo2 NaN too2
# 2 oo3 NaN too3
# 3 aa1 taa1 NaN
# 4 aa2 taa2 NaN
# 5 oo4 NaN too4
上面我想将注释列合并为一个。它们应该是互斥的(一个中的 nans 在另一个中具有值)。
这是我尝试过的:
m2["annotations"] = m2[pd.isnull(m2["annotations_x"])]["annotations_y"]
m2
# term annotations_x annotations_y annotations
# 0 oo1 NaN too1 too1
# 1 oo2 NaN too2 too2
# 2 oo3 NaN too3 too3
# 3 aa1 taa1 NaN NaN
# 4 aa2 taa2 NaN NaN
# 5 oo4 NaN too4 too4
m2["annotations"] = m2[pd.isnull(m2["annotations_y"])]["annotations_x"]
m2
# term annotations_x annotations_y annotations
# 0 oo1 NaN too1 NaN
# 1 oo2 NaN too2 NaN
# 2 oo3 NaN too3 NaN
# 3 aa1 taa1 NaN taa1
# 4 aa2 taa2 NaN taa2
# 5 oo4 NaN too4 NaN
我包含了整个很长的内容,因为我最初想做的事情可能只需几行就可以完成。因此,我不仅展示了我的最后一个问题,还包括了整个问题,因为如果我更聪明的话,我现在正在努力解决的最后一个问题可能会被避免。
【问题讨论】: