从CSV中删除尾随空格

时间:2014-12-17 07:31:09

标签: python csv pandas strip

我无法将stop_headsign的剥离空白传回stop_times以输出为CSV。或者,有.rstrip()整个stop_headsign列的方法吗?

Herestop_times.txt要点。

Here是pandas rstrip参考。

以下是我的代码:

import pandas as pd

stop_times = pd.read_csv('csv/stop_times.txt')

for x in stop_times['stop_headsign']:
    if type(x) == str:
        x = x.rstrip()
        # figure out how to pass store new value
    if type(x) == float:
        pass

stop_times['distance'] = 0

stop_times.to_csv('csv/stop_times.csv', index=False)

以下是csv输出显示的内容:

trip_id,arrival_time,departure_time,stop_id,stop_sequence,pickup_type,drop_off_type,stop_headsign,distance
568036,,,00382,26,0,0,78 UO                                             ,0
568036,,,00396,7,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00398,8,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00400,9,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00404,10,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00407,11,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00412,13,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00413,14,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00416,15,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00418,16,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00419,17,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00422,18,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00423,19,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00425,20,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,00427,21,0,0,78 UO <> 78 via 18th AVE                          ,0
568036,,,01006,2,0,0,78 UO <> 78 via 18th AVE                          ,0

1 个答案:

答案 0 :(得分:3)

Pandas在Series个对象上有一个方便的“扩展”属性:

stop_times["stop_headsign"] = stop_times["stop_headsign"].str.rstrip()

实际上,您的链接指向此链接,.str的类型为StringMethods

基础知识文档中有一个Vectorized String Methods部分链接到Working with Text Data

相关问题