繁体   English   中英

R 脚本到 Python 代码

[英]R script to Python code

我开始更深入地研究 Python,但在将我的一些 R 脚本转换为 Python 时遇到了麻烦。 我在 R 中定义了一个函数:

Shft_Rw <- function(x) { for (row in 1:nrow(x))
{
  new_row = x[row , c(which(!is.na(x[row, ])), which(is.na( x[row, ])))]
  colnames(new_row) = colnames(x)
  x[row, ] = new_row
}
  return(x)  
}

这基本上需要数据帧中每一行的前导 NA 并将它们放在行的末尾,即

import pandas as pd
import numpy as np
df =pd.DataFrame({'a':[np.nan,np.nan,3],'b':[3,np.nan,5],'c':[3, 4,5]})

df
Out[156]: 
     a    b  c
0  NaN  3.0  3
1  NaN  NaN  4
2  3.0  5.0  5

变成:

df2 =pd.DataFrame({'a':[3,4,3],'b':[3,np.nan,5],'c':[np.nan, np.nan,5]})
df2
Out[157]: 
   a    b    c
0  3  3.0  NaN
1  4  NaN  NaN
2  3  5.0  5.0

到目前为止,我有:

def Shft_Rw(x):
    for row in np.arange(0,x.shape[0]):
        new_row = x.iloc[row,[np.where(pd.notnull(x.iloc[row])),np.where(pd.isnull(df.iloc[row]))]]

但是抛出错误。 使用上面的示例 df 我可以使用 iloc 和列位置获得一个行索引,其中它为空/非空(使用 where()),但不能将两者放在一起(尝试了许多带有更多括号等的变体)。

df.iloc[1]
Out[170]: 
a    NaN
b    NaN
c    4.0

np.where(pd.isnull(df.iloc[1]))
In[167] :  np.where(pd.isnull(df.iloc[1]))
Out[167]: (array([0, 1], dtype=int64),)

df.iloc[1,np.where(pd.notnull(df.iloc[1]))]

任何能够帮助复制功能和/或展示解决问题的更有效方法的人?

谢谢!

使用applydropna

df1 = df.apply(lambda x: pd.Series(x.dropna().values), axis=1)
df1.columns = df.columns
print (df1)
     a    b    c
0  3.0  3.0  NaN
1  4.0  NaN  NaN
2  3.0  5.0  5.0

如果性能很重要,我建议使用这个完美的对齐功能

arr = justify(df.values, invalid_val=np.nan, axis=1, side='left')
df1 = pd.DataFrame(arr, index=df.index, columns=df.columns)
print (df1)
     a    b    c
0  3.0  3.0  NaN
1  4.0  NaN  NaN
2  3.0  5.0  5.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM