2017-06-26 98 views
2

我有數據幀,看起來像這樣...轉移細胞權類EXCEL

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

myst="""india, 905034 , 19:44 
USA, NULL, 905094 , 19:33 
Russia, 905154 , 21:56 
""" 
u_cols=['country', 'index', 'current_tm', 'dummy'] 

myf = StringIO(myst) 
import pandas as pd 
df = pd.read_csv(StringIO(myst), sep=',', names = u_cols) 

上面的代碼將生成一個表,看起來就像這樣......

country index current_tm dummy 
0 india 905034 19:44 NaN 
1 USA NULL 905094 19:33 
2 Russia 905154 21:56 NaN 

指數國家「USA」的值爲NULL。我需要刪除它並將右側的「905094」的值左移。以便最終的數據框看起來像這樣...

country index current_tm 
0 india 905034 19:44 
1 USA 905094 19:33 
2 Russia 905154 21:56 

在Excel中,我可以簡單地右鍵單擊以選擇「刪除...」並選擇左移選項單元。 Pandas中是否有類似的功能?

回答

2

存在的主要問題的不同類型 - 在current_tm列是strings,列indexfloat秒(因爲NaN S)和需要int秒。

所以第一fillnaNaN S,轉換爲int,然後str爲同一類型str

然後通過notnull得到掩碼,然後列,最後轉換爲intdrop列。

df['index'] = df['index'].fillna(0).astype(int).astype(str) 
cols = ['index', 'current_tm', 'dummy'] 
idx = df['dummy'].notnull().index 

df.loc[idx, cols] = df.loc[idx, cols].shift(-1, axis=1) 

df = df.drop('dummy', axis=1) 
df['index'] = df['index'].astype(int) 
print (df) 
    country index current_tm 
0 india 905034  19:44 
1  USA 905094  19:33 
2 Russia 905154  21:56