Pandas 转换某些字符串的NA值

Pandas 转换某些字符串的NA值,pandas,Pandas,如果特定字符串用于,我如何转发填充值,例如-”- 这是我的数据框: try: from StringIO import StringIO except ImportError: from io import StringIO myst="""india / gujarat, 22905034 , 19:44 india / kerala, -"- , 19:33 -"-, 905154 , 21:56 """ u_cols=['country_state', '

如果特定字符串用于,我如何转发填充值,例如-”-

这是我的数据框:

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

myst="""india / gujarat, 22905034 , 19:44   
india / kerala, -"-  , 19:33
-"-,  905154 ,   21:56

"""
u_cols=['country_state', 'index1', 'current_tm']

myf = StringIO(myst)
import pandas as pd
df = pd.read_csv(StringIO(myst), sep=',', names = u_cols, na_values=['-"-'])
我可以正确填写国家/地区列,但由于多余的空间,无法复制index1值

df.ffill()
更换似乎不起作用

df.index1.replace('-"-' , '')
有没有办法在读取csv方法中剥离并使用字符串作为na_值参数?

对于我来说:

df.index1 = df.index1.replace('\s*-"-\s*' , np.nan, regex=True)
但是如果想要使用
read_csv
,则必须使用
转换器

def conv(x):
    return np.nan if x.strip() == '-"-' else x.strip()

#define each column
convs={'index1': conv, 'current_tm': conv, 'country_state':conv}
df = pd.read_csv(StringIO(myst), converters=convs, names = u_cols)
print (df)
     country_state    index1 current_tm
0  india / gujarat  22905034      19:44
1   india / kerala       NaN      19:33
2              NaN    905154      21:56
对于我的工作:

df.index1 = df.index1.replace('\s*-"-\s*' , np.nan, regex=True)
但是如果想要使用
read_csv
,则必须使用
转换器

def conv(x):
    return np.nan if x.strip() == '-"-' else x.strip()

#define each column
convs={'index1': conv, 'current_tm': conv, 'country_state':conv}
df = pd.read_csv(StringIO(myst), converters=convs, names = u_cols)
print (df)
     country_state    index1 current_tm
0  india / gujarat  22905034      19:44
1   india / kerala       NaN      19:33
2              NaN    905154      21:56

使用分隔符
\s*,\s*
以便忽略起始和结束空格,na_值可以正常工作

df = pd.read_csv(StringIO(myst), sep='\s*,\s*', names = u_cols, na_values=['-"-'],engine='python')

country_state      index1 current_tm
0  india / gujarat  22905034.0      19:44
1   india / kerala         NaN      19:33
2              NaN    905154.0      21:56
您还可以导入然后替换na_值,即

df = pd.read_csv(StringIO(myst), sep=',', names = u_cols).replace('-"-', np.nan,regex=True)

使用分隔符
\s*,\s*
以便忽略起始和结束空格,na_值可以正常工作

df = pd.read_csv(StringIO(myst), sep='\s*,\s*', names = u_cols, na_values=['-"-'],engine='python')

country_state      index1 current_tm
0  india / gujarat  22905034.0      19:44
1   india / kerala         NaN      19:33
2              NaN    905154.0      21:56
您还可以导入然后替换na_值,即

df = pd.read_csv(StringIO(myst), sep=',', names = u_cols).replace('-"-', np.nan,regex=True)

虽然我觉得这是一个沉重的负担,我们可以在这里使用分离器虽然我觉得这是一个沉重的负担,我们可以在这里使用分离器