如果需要,Pandas会在字符之间添加空格

时间:2016-03-26 12:51:17

标签: python-3.x pandas

给出以下数据框:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A':['One[P]','Two [N]'],
})

df
    A
0   One[P]
1   Two [N]

我想在开括号之前添加一个空格('[')如果不存在(对于非常高的列)。

期望的结果是:

    A
0   One [P]
1   Two [N]

提前致谢!

2 个答案:

答案 0 :(得分:2)

或者,您可以使用RegEx' s:

import xlrd

file_location = "location/file_name.xlsx"

workbook = xlrd.open_workbook(file_location)

sheet = workbook.sheet_by_name('sheet')

x = []

for cell in sheet.col[9]:

    if isinstance(cell, float):

        x.append(cell)

print(x)

答案 1 :(得分:2)

或者您可以使用:

df.loc[~df.A.str.contains(r' \['), 'A'] = df.A.str.replace('[',' [')
print df
         A
0  One [P]
1  Two [N]