遍历行并将数据打印到新数据框

时间:2018-09-23 10:20:04

标签: python pandas

我的数据框是这样的:

rangeStart.unix()

我尝试了以下方法来遍历Pandas数据框中的行

1537567200

所需和必需的输出为:

     Rid          emonth             source                 Budget
      1           Jan18,Mar18        Video,webpage,email    5000
      2           Aug18              Editor,content         1200
      3           May18,Jul18        Webpage,video          300
      4           18-Dec             Designer               100

有人可以帮我逐行迭代并将输出打印到新的数据框中吗?

1 个答案:

答案 0 :(得分:2)

您可以使用字符串拆分并展开列

# Converting all columns to string
df = df.astype(str)
# Line by line looping through each row, splitting each row series with delimiter of ',' and expanding as dataframe. 
# Transpose will return the expanded columns as rows 
df = pd.concat([df.loc[x].str.split(',',expand=True).T for x in range(len(df))],0).reset_index(drop=True)
# filling none value 'Response id' with forward fill
df['Response_id'] = df['Response_id'].ffill()

出局:

    Rid           emonth               source      Budget
0   1             Jan18               Video             5000
1   1             Mar18              webpage            None
2   1             None                email             None
3   2             Aug18               Editor            1200
4   2             None               content            None
5   3             May18              Webpage            300
6   3             Jul18                video            None
7   4             18-Dec             Designer           100
相关问题