将空行附加到 Pandas 中的 Dataframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41764226/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:49:48  来源:igfitidea点击:

Append empty rows to Dataframe in pandas

pythonpandas

提问by Manuel Pasieka

I want to append empty rows (filled with np.NaN) to a pandas dataframe and currently only know how to do this using loc

我想将空行(用 np.NaN 填充)附加到 Pandas 数据帧,目前只知道如何使用 loc 执行此操作

T = pd.DataFrame(index=['a', 'b', 'c'], data={'Col0': 0, 'Col1': 1})
T
   Col0  Col1
a     0     1
b     0     1
c     0     1

missing = ['d', 'e']
for m in missing:
    T.loc[m] = np.NaN

  Col0  Col1
a   0.0   1.0
b   0.0   1.0
c   0.0   1.0
d   NaN   NaN
e   NaN   NaN

Do you know of a more elegantway to do this?

你知道一个更优雅的方式来做到这一点吗?

Why it is not possible to do something like

为什么不可能做这样的事情

T.loc[missing] = np.NaN

thx!

谢谢!

回答by EdChum

You can reindexby taking the unionof the current index and the missing row values:

您可以reindex通过获取union当前索引和缺失的行值:

In [281]:    
T.reindex(T.index.union(missing))

Out[281]:
   Col0  Col1
a   0.0   1.0
b   0.0   1.0
c   0.0   1.0
d   NaN   NaN
e   NaN   NaN

basically loclooks for the passed in labels, unfortunately setting with enlargementonly works for a single row label.

基本上loc寻找传入的标签,不幸的是,放大设置仅适用于单行标签。

It'd be more efficient to do the above, here we take the unionof the current index and the missing values and use these to reindexthe df, where rows don't exist NaNvalues are inserted.

执行上述操作会更有效,这里我们采用union当前索引和缺失值的 ,并将它们用于reindexdf,其中NaN插入了不存在的行值。

回答by Ted Petrou

You can use .locvery similarly to reindex

您可以.loc非常类似地使用reindex

df.loc[df.index.tolist() + missing]

回答by piRSquared

If you actually have a dataframe, you can use pd.concat

如果您确实有一个数据框,则可以使用 pd.concat

df = pd.DataFrame(index=missing)

pd.concat([T, df])

Or alternatively, you can use pd.DataFrame.append

或者,您可以使用 pd.DataFrame.append

df = pd.DataFrame(index=missing)

T.append(df)


Both yield:

两者产量:

   Col0  Col1
a   0.0   1.0
b   0.0   1.0
c   0.0   1.0
d   NaN   NaN
e   NaN   NaN