[英]How to append a new row on pandas dataframe with single column?
This question might seems easy but I could not find any solution for it. 这个问题似乎很容易,但我找不到任何解决方案。
Say I have a CSV file like this without headers. 假设我有一个没有标题的CSV文件。
121
334
313
930
I want to add/append new row with number 0
at the bottom like this 我想在底部添加/追加数字
0
新行,就像这样
121
334
313
930
0
I tried with the following method but did not succeed. 我试过以下方法,但没有成功。
import pandas as pd
import os
folder_path = "/home/Ling/test/"
df = pd.read_fwf(folder_path + "test1.csv", usecols=[0], delimiter=",")
df2 = pd.DataFrame([[0]], dtype=int)
print df.append(df2, ignore_index=True)
The result 结果
NaN 121
NaN 334
NaN 313
NaN 930
0.0 NaN
I am following this example 我正在关注这个例子
I even try to change from [[0]]
to [[0,]]
and [[,0]]
but did not work. 我甚至尝试从
[[0]]
改为[[0,]]
和[[,0]]
但是没有用。 Is there anything that I miss here in the code? 代号中有什么我想念的吗?
Thank you for your help and suggestion. 感谢您的帮助和建议。
import pandas as pd
import numpy as np
#read data frame with header None
df=pd.read_csv("datapath/df.csv",header=None)
df=df.append(pd.Series(np.array([0])),ignore_index=True)
You can add new row using loc
and shape
as well: 您也可以使用
loc
和shape
添加新行:
df.loc[df.shape[0]] = 0
Or if you want to use append
: 或者如果你想使用
append
:
df2 = pd.DataFrame([0])
df.append(df2, ignore_index=True)
Finally, when reading csv
add header=None
to imply that no column names are included. 最后,当读取
csv
添加header=None
表示不包含列名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.