为df行中的每个条目创建单行

时间:2017-09-25 08:39:38

标签: python pandas dataframe

您好我在excel文件中读取了一个DataFrame,其行包含多个值。 df的形状如下:

                                             Welding
0  65051020                                      ...
1  66053510                          66053550    ...
2  66553540                66553560              ...
3  67053540                  67053505            ...

现在我想拆分每一行并将每个条目写入自己的行,如

    Welding
0   65051020
1   66053510
2   66053550
....
n   67053505

我试过尝试过:

[new.append(df.loc[i,"Welding"].split()) for i in range(len(df))]

df2=pd.DataFrame({"Welding":new})

print(df2)

                                             Welding
0                                            66053510
1                                            66053550
2                                            66053540
3                                            66053505
4                                            66053551
5   [65051020, 65051010, 65051030, 65051035, 65051...
6   [66053510, 66053550, 66053540, 66053505, 66053...
7   [66553540, 66553560, 66553505, 66553520, 66553...
8                      [67053540, 67053505, 67057505]
9   [65051020, 65051010, 65051030, 65051035, 65051...
10  [66053510, 66053550, 66053540, 66053505, 66053...
11  [66553540, 66553560, 66553505, 66553520, 66553...
12                     [67053540, 67053505, 67057505]
13  [65051020, 65051010, 65051030, 65051035, 65051...
14  [66053510, 66053550, 66053540, 66053505, 66053...
15  [66553540, 66553560, 66553505, 66553520, 66553...
16                     [67053540, 67053505, 67057505]

但这并没有带来预期的结果。

感谢每一个帮助!

1 个答案:

答案 0 :(得分:1)

splitstackto_frame

一起使用
df = df['Welding'].str.split(expand=True).stack().reset_index(drop=True).to_frame('Welding')
print (df)
    Welding
0  65051020
1  66053510
2  66053550
3  66553540
4  66553560
5  67053540
6  67053505