Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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 添加缺少的列_Python_Pandas_Numpy_Dataframe_Encoding - Fatal编程技术网

Python 添加缺少的列

Python 添加缺少的列,python,pandas,numpy,dataframe,encoding,Python,Pandas,Numpy,Dataframe,Encoding,这个问题是问题的继续。 假设现在我们有2个数据帧,train和test,我如何能够为每个数据帧添加缺少的列? 问候, 编辑: 列车数据帧: Products 1 A;B 2 A 3 B;A;C Products 1 A;B 2 A 3 D;A;B 成为: Has_A Has_B Has_C

这个问题是问题的继续。 假设现在我们有2个数据帧,train和test,我如何能够为每个数据帧添加缺少的列? 问候,

编辑: 列车数据帧:

         Products
1           A;B
2           A
3           B;A;C
         Products
1           A;B
2           A
3           D;A;B
成为:

          Has_A      Has_B        Has_C   
1           1          1            0
2           1          0            0
3           1          1            1
          Has_A      Has_B      Has_D
1           1          1          0
2           1          0          0
3           1          1          1
测试数据帧:

         Products
1           A;B
2           A
3           B;A;C
         Products
1           A;B
2           A
3           D;A;B
成为:

          Has_A      Has_B        Has_C   
1           1          1            0
2           1          0            0
3           1          1            1
          Has_A      Has_B      Has_D
1           1          1          0
2           1          0          0
3           1          1          1
列车在每个加号中有“has_C”和测试有“has_D”

我想将Has_C列添加到测试中,将Has_D添加到列车中,并将其填充为0。

您可以使用以下方法:

演示:

我认为您需要或使用
列的

train = train['Products'].str.get_dummies(';').add_prefix('Has_')
test = test['Products'].str.get_dummies(';').add_prefix('Has_')

cols = train.columns.union(test.columns)
print (cols)
Index(['Has_A', 'Has_B', 'Has_C', 'Has_D'], dtype='object')

train = train.reindex_axis(cols, axis=1, fill_value=0)
print (train)
   Has_A  Has_B  Has_C  Has_D
1      1      1      0      0
2      1      0      0      0
3      1      1      1      0

test = test.reindex(columns=cols, fill_value=0)
print (test)
   Has_A  Has_B  Has_C  Has_D
1      1      1      0      0
2      1      0      0      0
3      1      1      0      1

//获取不在列中的列

cols=列表(设置(列测向列.值)-设置(测试测向列.值))

//创建虚拟数据帧并与列车连接

pd.DataFrame([[0代表cols中的col]],columns=cols).join(test_df,how='outer').fillna(0)

对列车进行相同的处理


希望有帮助:)

重复两次……两个集合中都没有某些值。您能解释更多吗?一些示例数据是最好的。编辑问题使用
.reindex\u axis(…)
-我喜欢它