英文:
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][['a','c']] = {'a':4,'c':5}
输出:-
|a|b|c|<br>
|4|2|5|
快速修复你的问题的方法是 -
test1_pd.loc[0, 'a'] = [{'x':1,'y':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]['a'] = {'a':4,'b':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][['a','c']] = {'a':4,'c':5}
Output:-
|a|b|c|<br>
|4|2|5|
A quick fix to your problem will be -
test1_pd.loc[0, 'a'] = [{'x':1,'y':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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论