从现有数据框架和索引创建新的 pandas 数据框架 [英] Creating new pandas DataFrame from existing DataFrame and index

查看:51
本文介绍了从现有数据框架和索引创建新的 pandas 数据框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的DataFrame:

I have a DataFrame like this:

  a b
A 1 0
B 0 1

我有一个数组["A","B","C"].

and I have an array ["A","B","C"].

从这些,我想创建一个新的DataFrame,如下所示:

From these, I want to create a new DataFrame like this:

  a   b
A 1   0
B 0   1
C NaN NaN

我该怎么做?

推荐答案

假设我了解您的要求(撇开奇怪的重复索引案例),一种方法是使用loc索引到您的框架中:

Assuming I understand what you're after (setting aside weird duplicated-index cases), one way is to use loc to index into your frame:

>>> df = pd.DataFrame({'a': {'A': 1, 'B': 0}, 'b': {'A': 0, 'B': 1}})
>>> arr = ["A", "B", "C"]
>>> df
   a  b
A  1  0
B  0  1
>>> df.loc[arr]
    a   b
A   1   0
B   0   1
C NaN NaN

这篇关于从现有数据框架和索引创建新的 pandas 数据框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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