我在每一行中保存了一个具有不同键的字典,在一个新的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我试图通过列表格式,同样的问题。我认为这是由于熊猫的过程。
提前谢谢你。
愿意接受任何解决方案来完成这项工作
发布于 2020-02-18 10:45:39
在增加字典后,您可以使用字典的副本分配给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)发布于 2020-02-18 11:34:35
多亏了无名氏,我找到了解决问题的办法,也许不是最好的选择,但因为我不需要表演。
这是我的代码,比他的代码效率低,但对于像我这样的初学者来说,理解起来可能更清楚(无意冒犯)。
import pandas as pd
import copy
def function():
#to skip the copy for the first (last) row
flag = 0
for x in reversed(range(20)):
if flag == 0:
dataset["dict_column"][x][str(dataset.value[x])][0] += 1
flag = 1
else:
dataset["dict_column"][x] = copy.deepcopy(dataset["dict_column"][x+1])
dataset["dict_column"][x][str(dataset.value[x])][0] += 1https://stackoverflow.com/questions/60278871
复制相似问题