基于列比较Python如何填充缺失值

2024-09-30 07:31:14 发布

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

我想将第2列中缺少的值填充到相应的第1列

import pandas as pd
data={"col1":["A","B","C","A","B","C","A","B","A"], "col2":["{hey1}"," ","{hello2}","{hey2}","{he1}","{hello3}","set()","set()","{hey1}"]}
df=pd.DataFrame(data=data)

它应该填充一些规则,如下所示: 例如,如果A出现四次,并且在4中,它有三次对应的col2值,第四次丢失, 所以缺失值应该是这三者的组合。在这个例子中,3个值是hey1,hey2,hey1。第四次失踪 应该包含hey2,hey1。 Set()是垃圾值,我不想要那个值。在处理列比较之前,我想删除它。 期望输出:

col1 col2
A     hey1
B    he1
C    hello2
A    hey2
B    he1
C     hello3
A    hey1,hey2
B    he1
A    hey1

Tags: importdataframepandasdfdataascol2col1
1条回答
网友
1楼 · 发布于 2024-09-30 07:31:14
data = {"col1": ["A", "B", "C", "A", "B", "C", "A", "B", "A"],
        "col2": ["", " ", "hello2", "hey2", "he1", "hello3", " ", "", ""]}
col1 = data["col1"]
col2 = data["col2"]

d = collections.defaultdict(list)
new_col2 = []
for i, tup in enumerate(list(zip(col1, col2))):
    key, value = tup
    if not value.strip():
        new_val = ", ".join(d[key])
        if not new_val:
            if len(new_col2) >= 1:
                new_val = new_col2[i - 1]
            else:
                new_val = ""

        new_col2.append(new_val)
    else:
        d[key].append(value)
        new_col2.append(value)

相关问题 更多 >

    热门问题