insert a column value based on index range

slayeroffrog :

I have a a Dataframe loaded from a .csv that looks like this

name          code
accounting
a             1
c             3
HR
b             2

I need to change so it reads like this

name  code  dept
a     1     accounting
c     3     accounting
b     2     HR

What can I do to achieve this?

Datanovice :

IIUC,

we can use .loc to assign to a new column, ffill and .dropna() to get your target df.

df.loc[df['code'].isnull(),'dept'] = df['name']

df['dept'] = df['dept'].ffill()

df_new = df.dropna(subset=['code'])

print(df_new)

  name  code        dept
1    a   1.0  accounting
2    c   3.0  accounting
4    b   2.0          HR

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13860&siteId=1