首页 > 解决方案 > Pandas 数据框在新列中反向增量字典

问题描述

我在新的 Dataframe 列中保存了每行中具有不同键的字典,并且所有值都等于 0。

从末尾开始,根据另一列(同一行)的值,我想增加这个字典,并存储这个字典的视图。

递增很好,但存储视图不起作用。最后,我在整个专栏中都有相同的字典。

Before
col1    col_dict
1       {1:0, 2:0, 3:0}
2       {1:0, 2:0, 3:0}
3       {1:0, 2:0, 3:0}

What i want:

col1    col_dict
1       {1:1, 2:1, 3:1}
2       {1:0, 2:1, 3:1}
3       {1:0, 2:0, 3:1}

What I have:

col1    col_dict
1       {1:1, 2:1, 3:1}
2       {1:1, 2:1, 3:1}
3       {1:1, 2:1, 3:1}

例如:

def function():
    for x in reversed(range(20)):
        #taking the value in the other column, and incrementing the value in the dictionary
        dataset["dict_column"][x][str(dataset.value[x])][0] += 1

我试图传递给列表格式,同样的问题。我认为这是由于熊猫的过程。

先感谢您。

愿意接受任何解决方案来完成这项工作

标签: pandasdataframedictionaryincrement

解决方案


您可以col_dict在增加字典后使用字典的副本进行分配。重新索引数据帧以确保反向增量。

import pandas as pd
import copy
df = pd.DataFrame()
df["col1"] = [1, 2, 3]

col_dict = {i:0 for i in df["col1"]}

def get_dict(col):
    col_dict[col] = 1
    return copy.copy(col_dict)

df = df.iloc[::-1]
df["col_dict"] = df["col1"].apply(get_dict)
df = df.iloc[::-1]
print(df)

推荐阅读