Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据索引范围插入列值_Python_Pandas - Fatal编程技术网

Python 根据索引范围插入列值

Python 根据索引范围插入列值,python,pandas,Python,Pandas,我有一个从.csv加载的数据帧,看起来像这样 name code accounting a 1 c 3 HR b 2 name code dept a 1 accounting c 3 accounting b 2 HR 我需要改变一下,让它看起来像这样 name code accounting a 1 c

我有一个从.csv加载的数据帧,看起来像这样

name          code
accounting
a             1
c             3
HR
b             2
name  code  dept
a     1     accounting
c     3     accounting
b     2     HR
我需要改变一下,让它看起来像这样

name          code
accounting
a             1
c             3
HR
b             2
name  code  dept
a     1     accounting
c     3     accounting
b     2     HR
我能做些什么来实现这一点?

IIUC

我们可以使用
.loc
分配给一个新列,
ffill
.dropna()
来获取您的目标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

这在档案里吗?一个数据帧?是一个数据帧,我更新了这个问题使它更清晰