python - 如何根据给定行中第 3 次出现的值获取列?

标签 python python-3.x pandas

我需要创建一个包含 10 列( float )的数据框,并且我需要确保每一行都有 5 个 Nan 值。

Data Frame Which I want to create 

A    B    C     D     E     F     G     H    I    J   
1.0  Nan  2.0   Nan   Nan   Nan   Nan   5.0  6.0  7.0
Nan  Nan  Nan   3.0   5.0   Nan   Nan   5.0  6.0  7.0
1.0   2.0  3.0   5.0   8.0   Nan   Nan   Nan  Nan  Nan
1.0   Nan  3.0   Nan  8.0   10.0  Nan   12.0  Nan  Nan

我想创建这种类型的数据集,其中每行有 5 个 NAN 值和 5 个有效值。我想为系列中的每一行返回第 3 次出现 Nan 值的列值。

  Expected Output 
  E (it has 3rd occurrence of Nan value in 1st row) 
  C (it has 3rd occurrence of Nan value in 2nd row)
  H (it has 3rd occurrence of Nan value in 3rd row)
  G (it has 3rd occurrence of Nan value in 4th row)

最佳答案

使用 cumsumargmax

df.columns[np.argmax(df.isnull().cumsum(1).eq(3).values,1)]
Out[788]: Index(['E', 'C', 'H', 'G'], dtype='object')

用于创建数据框

df=pd.DataFrame(np.random.randn(4, 10),columns=list('ABCDEFGHIJ'))
for x in range(len(df)):
    df.iloc[x,np.random.choice(10, 5, replace=False)]=np.nan
df
Out[783]: 
          A         B         C         D   E         F         G         H  \
0  1.263644       NaN -0.427018       NaN NaN  0.160732  0.033323 -1.285068   
1       NaN  2.713568 -0.964603  1.456543 NaN       NaN  0.201837  1.034501   
2       NaN       NaN       NaN -0.262311 NaN  0.361472 -0.089562  0.478207   
3       NaN  1.497916 -0.324090       NaN NaN       NaN  0.711363 -0.094587   
    I         J  
0 NaN       NaN  
1 NaN       NaN  
2 NaN  0.944062  
3 NaN -0.298129  

关于python - 如何根据给定行中第 3 次出现的值获取列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51255869/

相关文章:

python - 使用 Pandas 从 zip 中读取特定的 csv 文件

python : I'm unable to fix TypeError: 'str' object is not callable

python - 如何在nosetests中使用正则表达式(即-m)在夹具中选择一些测试方法?

python-3.x - 将 CSV 导入 pandas 数据框,以列表作为列

python - 在 HTML 中运行 Python 脚本

python - 如何使用stepic.encode()

python - 使用 Python 中的日期列表循环 24 小时周期

python - 将对象转换为 pandas 中的 float 对象并替换 $ 符号

python - 在两个值之间切换的 Pythonic 方式是什么?

python - 不可哈希类型 : 'list'