移动细胞与Excel相似



我有看起来像这样的dataFrame ...

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

国家"美国"的索引值无效。我需要将其删除,并将右上" 905094"的值转移到左侧。这样最终的数据框将看起来像这样...

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

在Excel中,我可以右键单击以选择"删除...",然后选择"换档单元格"左选项。熊猫中是否有类似的功能?

存在主要问题不同类型 - 列中current_tm中的是strings,在index CC_3 float s中(因为NaN s(,并且需要intS。

因此,首先fillna NaN S,转换为int,然后转换为相同类型的str

然后通过notnull获取Mask,然后获取shift COLS,最后转换为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

相关内容

最新更新