Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建1s&;的关键列;基于NaN的0s映射_Python_Pandas_Dataframe_Nan - Fatal编程技术网

Python 创建1s&;的关键列;基于NaN的0s映射

Python 创建1s&;的关键列;基于NaN的0s映射,python,pandas,dataframe,nan,Python,Pandas,Dataframe,Nan,我有一个数据帧,如下所示: df A、B、C、D、E 0测试NaN 10.0 a 1测试NaN 10.0 a 2个测试x NaN a NaN 3测试NaN 12.0 NaN NaN 4测试x楠楠楠楠 5试验NaN 14.0克c 我想创建一个键列,其中: 是一个长度==len(df.columns) 每个0表示NaN,每个1表示不NaN A B C D E键 0测试NaN 10.0 a 10111 1测试NaN 10.0 a 10111 2个测试x NaN a NaN 11010 3测试Na

我有一个
数据帧
,如下所示:

df
A、B、C、D、E
0测试NaN 10.0 a
1测试NaN 10.0 a
2个测试x NaN a NaN
3测试NaN 12.0 NaN NaN
4测试x楠楠楠楠
5试验NaN 14.0克c
我想创建一个
列,其中:

  • 是一个长度==
    len(df.columns)
  • 每个
    0
    表示
    NaN
    ,每个
    1
    表示不
    NaN
A B C D E键
0测试NaN 10.0 a 10111
1测试NaN 10.0 a 10111
2个测试x NaN a NaN 11010
3测试NaN 12.0 NaN 10100
4个测试x南11000
5试验NaN 14.0 g c 10111
我知道如何检查它,但不知道如何将它放入一列中的一个字符串中。我目前的代码是:

对于df.列中的列:
...     打印(df[col].isnull().astype(int).replace({1:0,0:1}))
...     
0    1
1    1
2    1
3    1
4    1
5    1
名称:A,数据类型:int64
0    0
1    0
2    1
3    0
4    1
5    0
名称:B,数据类型:int64
0    1
1    1
2    0
3    1
4    0
5    1
名称:C,数据类型:int64
0    1
1    1
2    1
3    0
4    0
5    1
名称:D,数据类型:int64
0    1
1    1
2    0
3    0
4    0
5    1
名称:E,数据类型:int64
0    1
1    1
2    1
3    1
4    1
5    1
名称:key,数据类型:int64
与和一起使用:


另一种方法:

与和一起使用:


另一种方法:


使用numpy和列表理解

df['key'] = [''.join(x) for x in np.where(df.isnull(),'0','1')]


使用numpy和列表理解

df['key'] = [''.join(x) for x in np.where(df.isnull(),'0','1')]

df['key'] =  df.notna().astype(int).astype(str).stack().groupby(level=0).agg(''.join)
df['key'] = [''.join(x) for x in np.where(df.isnull(),'0','1')]
print(df)

      A    B     C    D    E    key
0  test  NaN  10.0    a    a  10111
1  test  NaN  10.0    a    a  10111
2  test    x   NaN    a  NaN  11010
3  test  NaN  12.0  NaN  NaN  10100
4  test    x   NaN  NaN  NaN  11000
5  test  NaN  14.0    g    c  10111