将标头添加到 DataFrame Pandas
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52479310/
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 06:02:46 来源:igfitidea点击:
Adding Header to a DataFrame Pandas
提问by Sriram Arvind Lakshmanakumar
i have a DataFrame:
我有一个数据帧:
Index 1 Dr. Santosh Kumar
0 NaN BHR/ 6681/148/1/134094/2007-08/L
1 NaN B/301, Laxmi Apartment
2 NaN New Chitragupta Nagar, Kankerbagh
3 NaN Patna a“ 800 020
4 NaN NaN
5 2 Dr. Deepak Kumar
6 NaN BHR/ 6682/148/2/134095/2007-08/L
7 NaN At & P.o- Bairia
8 NaN P.s- Gourichak
9 NaN Patna a“ 800 007
i want to add an header to this dataframe,
我想向这个数据帧添加一个标题,
df = pd.DataFrame([df],columns = ["id","information"])
but i get this error:
但我收到此错误:
ValueError: Shape of passed values is (1, 1), indices imply (2, 1)
so final output should be:
所以最终输出应该是:
Index id information
0 1 Dr. Santosh Kumar
1 NaN BHR/ 6681/148/1/134094/2007-08/L
2 NaN B/301, Laxmi Apartment
3 NaN New Chitragupta Nagar, Kankerbagh
4 NaN Patna a“ 800 020
5 NaN NaN
6 2 Dr. Deepak Kumar
7 NaN BHR/ 6682/148/2/134095/2007-08/L
8 NaN At & P.o- Bairia
9 NaN P.s- Gourichak
10 NaN Patna a“ 800 007
回答by piRSquared
Try:
尝试:
df = pd.DataFrame(
np.row_stack([df.columns, df.values]),
columns=['id', 'information']
)
回答by jezrael
You can add columns names by parameter names
in read_csv
if no header file:
您可以通过参数添加列名names
中read_csv
如果没有头文件:
df = pd.read_csv(file, names=["id","information"])
If want set columns names by list:
如果要按列表设置列名称:
df.columns = ["id","information"]