>>> z=pd.DataFrame([['abcb','asasa'],['sdsd','aeio']])
>>> z
0 1
0 abcb asasa
1 sdsd aeio
>>> u=pd.DataFrame(z,columns=['hello','ajsajs'])
>>> u
hello ajsajs
0 NaN NaN
1 NaN NaN
u = z.set_axis(['hello','ajsajs'], axis=1, inplace=False)
关于set_axis中inplace的一个小注-
WARNING: inplace=None currently falls back to to True, but in a future
version, will default to False. Use inplace=True explicitly rather
than relying on the default.
from pandas.core.internals import BlockManager
# pandas.core.frame.DataFrame
class DataFrame(NDFrame):
def __init__(self, data=None, index=None, columns=None, dtype=None,
copy=False):
# ...
if isinstance(data, DataFrame):
data = data._data
if isinstance(data, BlockManager):
mgr = self._init_mgr(data, axes=dict(index=index, columns=columns),
dtype=dtype, copy=copy)
# ... a bunch of other if statements irrelevant to your case
NDFrame.__init__(self, mgr, fastpath=True)
# ...
# pandas.core.generic.NDFrame
class NDFrame(PandasObject, SelectionMixin):
def __init__(self, data, axes=None, copy=False, dtype=None,
fastpath=False):
# ...
def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
""" passed a manager and a axes dict """
for a, axe in axes.items():
if axe is not None:
mgr = mgr.reindex_axis(axe,
axis=self._get_block_manager_axis(a),
copy=False)
# ...
return mgr
交替构造调用
您可以使用基础NumPy数组:
或者,您可以使用:
最后,正如@Dark所建议的:
关于
set_axis
中inplace
的一个小注-在pandas 0.20.3中,语法仅为:
@Dark的解决方案在这里出现得最快。你知道吗
为什么当前方法不起作用
我认为这里的问题是,当以这种方式构造数据帧时,会调用
.reindex
。以下是一些源代码,其中省略号表示我遗漏的不相关的内容:这里发生了什么:
u = pd.DataFrame(z,columns=['hello','ajsajs'])
中,x
是一个数据帧。因此,下面的第一个if
语句是True,data = data._data
。什么是_data
?是^{if
语句的计算结果也是True。然后mgr
被分配给_init_mrg
方法的结果,父类的__init__
被调用,传递mgr
。你知道吗*用
isinstance(z._data, BlockManager)
确认。你知道吗现在进入第二部分。。。你知道吗
这里是定义
_init_mgr
的地方,上面会调用它。基本上,在你的情况下,你有:当您转到“重新索引轴”(reindex axis)并指定一个新轴(旧对象中不包含任何新标签)时,您将得到所有的NaN。这似乎是一个深思熟虑的设计决策。考虑这个相关的例子来证明这一点,其中一个新列存在,一个不存在:
相关问题 更多 >
编程相关推荐