2017-11-25 70 views
1

如果將特定字符串用於例如 - 「 -將某些字符串的NA值轉換爲

這裏是我的數據框:

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=['-"-']) 

我能正確填寫全國列,但由於額外的空間索引1的值不會被複制

df.ffill() 

更換似乎並沒有工作。

df.index1.replace('-"-' , '') 

是否有任何方法去掉,然後使用字符串作爲na_values參數閱讀csv方法嗎?

回答

2

使用分離器\s*,\s*所以初始和結尾空格會被忽略,na_values將做工精細

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 

你也可以im端口,然後替換na_values,即

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

爲我工作:

df.index1 = df.index1.replace('\s*-"-\s*' , np.nan, regex=True) 

但是,如果想使用read_csv然後converters是必要的:

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 
+0

雖然我覺得它很沉重,但我們可以在這裏使用分隔符 – Dark