pandas 如何在忽略索引对齐的情况下分配列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15979339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign columns while ignoring index alignment
提问by Amelio Vazquez-Reina
Say I have two dataframes xand yin Pandas, I would like to fill in a column in xwith the result of sorting a column in y. I tried this:
假设我有两个数据框x,y在 Pandas 中,我想x用对y. 我试过这个:
x['foo'] = y['bar'].order(ascending=False)
but it didn't work, I suspectbecause Pandas aligns indicesbetween xand y(which have the same set of indices) during the assignment
但它没有用,我怀疑是因为 Pandas在分配期间对齐了x和y(具有相同的一组索引)之间的索引
How can I have Pandas fill in the x['foo']with another column from another dataframe ignoringthe alignment of indices?
我怎样才能让 Pandasx['foo']用另一个数据框中的另一列填充而忽略索引的对齐方式?
回答by DSM
The simplest way I can think of to get pandasto ignore the indices is to give it something without indices to ignore. Starting from
我能想到的pandas忽略索引的最简单方法是给它一些没有要忽略的索引的东西。从...开始
>>> 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
Or an unaligned one, by setting x["foo"]to a list:
或者一个未对齐的,通过设置x["foo"]为一个列表:
>>> x["foo"] = y["bar"].order(ascending=False).tolist()
>>> x
foo
1 33
2 22
0 11

