如何将字典类型的值分配给pandas数据框中的一个元素

huangapple go评论52阅读模式
英文:

How to assign dict type value to one element of a pandas dataframe

问题

如何将字典类型的值分配给pandas数据框架的一个元素。
Pandas版本为1.5.3;Python版本为3.9

例如:

import pandas as pd
test1_pd = pd.DataFrame([[1,2,3]], columns=['a','b','c'])
test2_pd = pd.DataFrame([[1,2,3]], columns=['a','b','c'])
test1_pd.loc[0]['a'] = {'x':1,'y':2}
test2_pd.loc[0]['a'] = 9

结果如下:

test1_pd
Out[116]: 
   a  b  c
0  1  2  3

test2_pd
Out[117]: 
   a  b  c
0  9  2  3

为什么test1_pd['a'][0]没有被字典值{‘x’:1,‘y’:2}替换?
但test2_pd['a'][0]成功被替换为9。

英文:

How to assign dict type value to one element of a pandas dataframe.
Pandas version is 1.5.3; python version is 3.9

for example:

import pandas as pd
test1_pd = pd.DataFrame([[1,2,3]], columns=['a','b','c'])
test2_pd = pd.DataFrame([[1,2,3]], columns=['a','b','c'])
test1_pd.loc[0]['a'] = {'x':1,'y':2}
test2_pd.loc[0]['a'] = 9

the result is:

test1_pd
Out[116]: 
   a  b  c
0  1  2  3

test2_pd
Out[117]: 
   a  b  c
0  9  2  3

Why test1_pd['a'][0] is not replaced by dict value {'x':1,'y':2}?
But test2_pd['a'][0] is replaced by 9 successfully.

答案1

得分: 0

即使 @Vvvvvv 在回答中添加了链接,还想添加一些有趣的见解到这个主题中。

在你的情况下,当你尝试分配字典时,pandas 的默认行为是尝试在字典中查找键 'a' 并将 'a' 的值分配给数据框中的列 'a'。

test1_pd.loc[0]['a'] = {'a':4,'b':5}

输出:-

|a|b|c|<br>
|4|2|3|

(对于以这种方式显示输出,我表示歉意),在你的情况下要索引的列('a')将在字典中查找,因此当你的键为 'x' 和 'y' 时,因为这些变量不是你数据框中的列名,所以没有值发生变化。另一个例子是

test1_pd.loc[0][[&#39;a&#39;,&#39;c&#39;]] = {&#39;a&#39;:4,&#39;c&#39;:5}

输出:-

|a|b|c|<br>
|4|2|5|

快速修复你的问题的方法是 -

test1_pd.loc[0, &#39;a&#39;] = [{&#39;x&#39;:1,&#39;y&#39;:2}]

以列表的形式呈现值,其中列表中的元素数量将等于列中的值数量。

英文:

Even though @Vvvvvv added the link to the answer, would like to add some interesting insights to the topic.

In your case, when you try to assign the dictionary, the default nature of pandas will try to look for the key 'a' inside the dictionary and assign the value of 'a' to the column 'a' in the dataframe.

test1_pd.loc[0][&#39;a&#39;] = {&#39;a&#39;:4,&#39;b&#39;:5}

Output:-

|a|b|c|<br>
|4|2|3|

(Apologies for displaying the output like this), The columns that are to be indexed ('a') in your case will be looked inside the dictionary, and hence no value changes when you have the keys as 'x' and 'y' because these variables are not the column names in your dataframe. Another example is

test1_pd.loc[0][[&#39;a&#39;,&#39;c&#39;]] = {&#39;a&#39;:4,&#39;c&#39;:5}

Output:-

|a|b|c|<br>
|4|2|5|

A quick fix to your problem will be -

test1_pd.loc[0, &#39;a&#39;] = [{&#39;x&#39;:1,&#39;y&#39;:2}]

presenting the values in the form of a list where number of elements in the list will be equal to the number of values in the column.

huangapple
  • 本文由 发表于 2023年6月5日 11:27:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定