将标题添加到DataFrame熊猫

时间:2018-09-24 12:22:20

标签: python pandas dataframe

我有一个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 – 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 – 800 007

我要向此数据帧添加标题

df = pd.DataFrame([df],columns = ["id","information"])

但我收到此错误:

ValueError: Shape of passed values is (1, 1), indices imply (2, 1)

因此最终输出应为:

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 – 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 – 800 007

2 个答案:

答案 0 :(得分:4)

如果没有头文件,则可以通过names中的参数read_csv添加列名称:

df = pd.read_csv(file, names=["id","information"])

如果要按列表设置列名:

df.columns = ["id","information"]

答案 1 :(得分:3)

尝试:

df = pd.DataFrame(
    np.row_stack([df.columns, df.values]),
    columns=['id', 'information']
)