如何在忽略索引对齐的同时分配列 [英] How to assign columns while ignoring index alignment
问题描述
说我在熊猫中有两个数据框x
和y
,我想用对y
中的一列进行排序的结果来填充x
中的一列.我试过了:
Say I have two dataframes x
and y
in Pandas, I would like to fill in a column in x
with the result of sorting a column in y
. I tried this:
x['foo'] = y['bar'].order(ascending=False)
但是它不起作用,我怀疑,因为熊猫在分配过程中在x
和y
(具有相同的索引集)之间将索引对齐
but it didn't work, I suspect because Pandas aligns indices between x
and y
(which have the same set of indices) during the assignment
如何让Pandas用另一个数据框中的另一列填充x['foo']
忽略索引的对齐方式?
How can I have Pandas fill in the x['foo']
with another column from another dataframe ignoring the alignment of indices?
推荐答案
我想到的最简单的方法是使pandas
忽略索引是给它一些不带索引的东西.从
The simplest way I can think of to get pandas
to ignore the indices is to give it something without indices to ignore. Starting from
>>> x = pd.DataFrame({"foo": [10,20,30]},index=[1,2,0])
>>> y = pd.DataFrame({"bar": [33,11,22]},index=[0,1,2])
>>> x
foo
1 10
2 20
0 30
>>> y
bar
0 33
1 11
2 22
我们采用通常的统一方法:
We have the usual aligned approach:
>>> x["foo"] = y["bar"].order(ascending=False)
>>> x
foo
1 11
2 22
0 33
或将列表中的x["foo"]
设置为未对齐的
Or an unaligned one, by setting x["foo"]
to a list:
>>> x["foo"] = y["bar"].order(ascending=False).tolist()
>>> x
foo
1 33
2 22
0 11
这篇关于如何在忽略索引对齐的同时分配列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!