在熊猫中划分列

时间:2017-04-11 10:22:03

标签: python-3.x pandas dataframe

我尝试弄清楚代码出了什么问题已经有一段时间了,但我想我需要帮助。这是我的问题。我有两个数据帧,我想彼此分开,但结果总是NaN。

In: merged.head()
Out: 
                     15           25          35          45          55  \
Wavelength                                                                 
460         1400.008821   770.372081  585.551187  547.150493  570.912408   
470         1525.470457   807.362906  573.020215  500.984110  489.206952   
480         1848.337785   873.034042  524.651886  410.963453  351.929723   
490         2214.989164   992.325996  566.273806  413.544512  340.781474   
500         2901.445401  1353.389196  807.889110  648.437549  615.930982   

In: white.head()
Out: 
                 White
Wavelength            
460         289.209506
470         366.083846
480         473.510106
490         524.090532
500         553.715322

当我尝试分工时,结果是:

In: ref = merged.div(white.White,axis = 0)
In: ref.head()
Out: 
            15  25  35  45  55  65  75  85
Wavelength                                
460        NaN NaN NaN NaN NaN NaN NaN NaN
470        NaN NaN NaN NaN NaN NaN NaN NaN
480        NaN NaN NaN NaN NaN NaN NaN NaN
490        NaN NaN NaN NaN NaN NaN NaN NaN
500        NaN NaN NaN NaN NaN NaN NaN NaN

在这种情况下,我的代码出了什么问题? 我也试试

ref = merged[["15","25","35","45","55","65","75","85"]].div(white.White,axis = 0)

具有相同的结果

1 个答案:

答案 0 :(得分:2)

我认为问题在索引的dtype不同,数据未对齐,因此获取NaN s - 需要相同。

#sample dtypes, maybe swapped
print (merged.index.dtype)
object
print (white.index.dtype)
int64

因此,解决方案是按astype转换索引:

merged.index = merged.index.astype(int)
white.index = white.index.astype(int)

或者:

merged.index = merged.index.astype(str)
white.index = white.index.astype(str)
#white.index is int, not necessary cast
merged.index = merged.index.astype(int)
ref = merged.div(white.White,axis = 0)
print (ref)
                  15        25        35        45        55
Wavelength                                                  
460         4.840812  2.663716  2.024661  1.891883  1.974044
470         4.166997  2.205404  1.565270  1.368496  1.336325
480         3.903481  1.843750  1.108006  0.867909  0.743236
490         4.226348  1.893425  1.080489  0.789071  0.650234
500         5.239959  2.444197  1.459033  1.171067  1.112360