Pandas dataframe反向增量字典在新列中

问题描述 投票:0回答:1

我在每行中保存了具有不同键的字典,在新的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

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

先谢谢您。

接受任何解决方案以完成工作

pandas dataframe dictionary increment
1个回答
0
投票

增加字典后,您可以使用字典的副本来分配给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)
© www.soinside.com 2019 - 2024. All rights reserved.