在pandas DataFrame中移动一个" cell"到另一个

时间:2017-10-14 16:31:44

标签: python pandas dataframe

我需要将pandas DataFrame中的对象从一个位置移动到另一个位置,并将该对象的原始位置留空而不影响其他列。

employees = [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
levels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

df = pd.DataFrame({"Employees":employees, "Level":levels})

#move employee 1 from index 3 to index 1 without altering Level column
#leave index 3 blank after moving employee 1

从视觉上看,我需要从starting point转到end point

谢谢!

2 个答案:

答案 0 :(得分:0)

这是我的解决方案。您可以使用.loc函数,该函数将索引作为第一个参数,列名作为第二个参数。

了解更多here

import pandas as pd
import numpy as np

employees = [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
levels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
df = pd.DataFrame({"Employees":employees, "Level":levels})

#substitution logic
temp = df['Employees'][3]
df.loc[3, 'Employees'] = ''
df.loc[1, 'Employees'] = temp
#print output
print df

<强>输出:

 Employees  Level
0         0      1
1         1      2
2         0      3
3                4
4         0      5
5         0      6
6         0      7
7         0      8
8         0      9
9         0     10

答案 1 :(得分:0)

使用:

df = pd.DataFrame({"Employees":['','','','empployee_object','','','','','',''], 
                   "Level":range(1,11)}, index=range(1,11))
print (df)
           Employees  Level
1                         1
2                         2
3                         3
4   empployee_object      4
5                         5
6                         6
7                         7
8                         8
9                         9
10                       10

#move value from 4 index to 2 index in Employees column
df.loc[2, 'Employees'] = df.loc[4, 'Employees']
#set empty string to original
df.loc[4, 'Employees'] = ''
print (df)
           Employees  Level
1                         1
2   empployee_object      2
3                         3
4                         4
5                         5
6                         6
7                         7
8                         8
9                         9
10                       10