2014-09-10 44 views
1

我有蟒蛇大熊猫以下数据帧:Python的熊猫更换楠的一列条件上观察另一列

current_data = pd.DataFrame({'X': ['3'+'*NY', '3', '2', '2'+'*NY', '1', '7'], 'Y': [np.nan, 4, 5, np.nan, 8, np.nan]}) 

我想要得到的是:

needed_data = pd.DataFrame({'X': ['3'+'*NY', '3', '2', '2'+'*NY', '1', '7'], 'Y': [4, 4, 5, 5, 8, np.nan]}) 

所以,我想要将与X中的观察值相对应的Y列与“* NY”部分替换为与Y中与具有相同的数字部分但没有“* NY”的观测值相对应的Y中的数字

+0

你的代码不能运行,这是一个有点不清楚,你能张贴所需的输出 – EdChum 2014-09-10 10:56:39

+0

的代码必须工作现在。我没有得到如何在这里发布python输出,所以我发布为代码 – izhak 2014-09-10 11:20:25

+0

因为你的代码没有工作,我无法想象所需的输出,现在我可以。然而,你的解释是一个令人困惑的问题,对于你想查找相应的'Y'值的Y值是'NaN',其中'X'值与'3xNY'的数值组件匹配正确吗? – EdChum 2014-09-10 11:23:21

回答

1

这是多一点讨厌的代码,基本上我们可以应用为您执行查找的自定义功能:

In [106]: 
# define our function 
def func(x): 
    # test to see if the asterisk is present 
    if x.find('*') > 0: 
     # perform a lookup on a slice of the passed in string 
     return(current_data.loc[current_data.X==x[0:x.find('*')],'Y'].values.max()) 
# using loc assign to column 'Y' where it is null the returned calculation of the apply 
current_data.loc[current_data.Y.isnull(),'Y'] = current_data[current_data.Y.isnull()]['X'].apply(func) 
current_data 
Out[106]: 
     X Y 
0 3*NY 4 
1  3 4 
2  2 5 
3 2*NY 5 
4  1 8 
5  7 NaN 
+0

确实如此:)谢谢你我想我将不得不花一个小时左右才能得到它的工作原理,但无论如何谢谢 – izhak 2014-09-10 13:15:26