如何在熊猫中相互替换多列

时间:2018-08-31 09:14:29

标签: pandas dataframe data-analysis

现在,我正在处理一个分析项目。实际上,我发现有些数据行被弄乱了。像这样:

  Data in 'Direction' column should be in 'Size' column

  Data in 'Size' column should be in 'Floor' column

  Data in 'Renovation' column should be in 'Direction' 

因此,我需要进行修改,即修改“方向”和“装修”,如下所示:

direction = modify_house.Renovation
modify_house.loc[:, 'Direction'] = direction

但是,它随后会发出错误警告:

/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py:543: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

因此,如何解决?还是有任何方法可以将这些数据放在正确的位置?谢谢!

1 个答案:

答案 0 :(得分:1)

按字典将rename与新旧列名一起使用:

modify_house= pd.DataFrame({'A':list('abcdef'),
                           'Size':[4,5,4,5,5,4],
                           'Direction':[7,8,9,4,2,3],
                           'Renovation':[1,3,5,7,1,0],
                           'E':[5,3,6,9,2,4],
                           'F':list('aaabbb')})

print (modify_house)
   A  Size  Direction  Renovation  E  F
0  a     4          7           1  5  a
1  b     5          8           3  3  a
2  c     4          9           5  6  a
3  d     5          4           7  9  b
4  e     5          2           1  2  b
5  f     4          3           0  4  b

d = {'Direction':'Size', 'Size':'Floor','Renovation':'Direction'}
modify_house = modify_house.rename(columns=d)
print (modify_house)
   A  Floor  Size  Direction  E  F
0  a      4     7          1  5  a
1  b      5     8          3  3  a
2  c      4     9          5  6  a
3  d      5     4          7  9  b
4  e      5     2          1  2  b
5  f      4     3          0  4  b

编辑:如果要创建新列或覆盖现有列,请使用assign

modify_house = modify_house.assign(Size=modify_house['Direction'], 
                                   Floor=modify_house['Size'], 
                                   Direction=modify_house['Renovation'])
print (modify_house)
   A  Size  Direction  Renovation  E  F  Floor
0  a     7          1           1  5  a      4
1  b     8          3           3  3  a      5
2  c     9          5           5  6  a      4
3  d     4          7           7  9  b      5
4  e     2          1           1  2  b      5
5  f     3          0           0  4  b      4