将空行附加到 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
Append empty rows to Dataframe in pandas
提问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 reindex
by taking the union
of 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 loc
looks 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 union
of the current index and the missing values and use these to reindex
the df, where rows don't exist NaN
values are inserted.
执行上述操作会更有效,这里我们采用union
当前索引和缺失值的 ,并将它们用于reindex
df,其中NaN
插入了不存在的行值。
回答by Ted Petrou
You can use .loc
very 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