如何在忽略索引对齐的同时分配列 [英] How to assign columns while ignoring index alignment

查看:54
本文介绍了如何在忽略索引对齐的同时分配列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在熊猫中有两个数据框xy,我想用对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)

但是它不起作用,我怀疑,因为熊猫在分配过程中在xy(具有相同的索引集)之间将索引对齐

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆