[英]Pandas: adding a column to a dataframe from dictionary, when keys are the indices of the dataframe
[英]Adding a column to pandas dataframe using dictionary with indices
这一定是微不足道的,但我就是找不到。
对于具有某些索引的给定idx2
dataframe
idx2
,例如idx1
、 idx2
、 idx3
我想使用字典有效地添加一个新列,如下所示:
最好的方法是什么?
have = pd.DataFrame({"idx1":{"c1":1,"c2":2}, \
"idx2":{"c1":3,"c2":4}, \
"idx3":{"c1":5,"c2":6}}).transpose()
newColumn = {"idx1":"col","idx2":"to","idx3":"add"}
columnName = "myName"
#Wished output:
want = pd.DataFrame({"idx1":{"c1":1,"c2":2,"myName":"col"}, \
"idx2":{"c1":3,"c2":4,"myName":"to"}, \
"idx3":{"c1":5,"c2":6,"myName":"add"}}).transpose()
have[columnName] = pd.Series(newColumn)
输出 :
>> have
c1 c2 myName
idx1 1 2 col
idx2 3 4 to
idx3 5 6 add
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.