Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.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 - Fatal编程技术网

Python 创建字符串数组

Python 创建字符串数组,python,pandas,numpy,Python,Pandas,Numpy,我有各种类型的标志数组,如: Data Type1 Type2 Type3 12 1 0 0 14 0 1 0 3 0 1 0 45 0 0 1 我要创建以下数组: Data TypeName 12 Type1 14 Type2 3 Type2 45 Type3 我尝试创建类型字符串的空数组,如下所示: import numpy as np z1 = np.empty(

我有各种类型的标志数组,如:

Data Type1 Type2 Type3
12   1     0     0
14   0     1     0
3    0     1     0
45   0     0     1
我要创建以下数组:

Data TypeName
12   Type1   
14   Type2   
3    Type2   
45   Type3   
我尝试创建类型字符串的空数组,如下所示:

import numpy as np
z1 = np.empty(4, np.string_)
z1[np.where(Type1=1)] = 'Type1'
但这似乎并没有给我想要的结果

编辑: 我可以使用pandas数据帧,每行只有1种类型,即Type1、Type2、Type3

编辑2:
数据类型1类型2类型3是熊猫数据框中的列名,但我在上面的示例中使用了带有隐式名称的numpy数组。

更新:这里是使用方法和使用
set_index()
reset_index()
的混合,以摆脱
pd.concat()

旧答案:

您可以这样做(解决方案):


一种方法是通过

df.apply(lambda row: 'Type1' if row.Type1 else 'Type2' if row.Type2 else 'Type3', axis=1)
例如:

In [6]: df
Out[6]: 
   Data  Type1  Type2  Type3
0    12      1      0      0
1    14      0      1      0
2     3      0      1      0
3    45      0      0      1

In [7]: df['TypeName'] = df.apply(lambda row: 'Type1' if row.Type1 else 'Type2' if row.Type2 else 'Type3', axis=1)

In [9]: df.drop(['Type1', 'Type2', 'Type3'], axis=1)
Out[9]: 
   Data TypeName
0    12    Type1
1    14    Type2
2     3    Type2
3    45    Type3
这里有一种方法滥用了这样一个事实,即我们从
Type1
列开始,每行只有一个
1
,使用
idxmax()-

pd.concat((df.Data, df.iloc[:,1:].idxmax(1)),axis=1)
样本运行-

In [42]: df
Out[42]: 
   Data  Type1  Type2  Type3
0    12      1      0      0
1    14      0      1      0
2     3      0      1      0
3    45      0      0      1

In [43]: pd.concat((df.Data, df.iloc[:,1:].idxmax(1)),axis=1)
Out[43]: 
   Data      0
0    12  Type1
1    14  Type2
2     3  Type2
3    45  Type3

输入是一个数据帧吗?从第二列开始的每一行是否总是有一个
1
?您能告诉我们如何创建这样的输入数组吗?我非常喜欢这个解决方案。实际上你不需要
pd.concat
-
df.set\u index('Data').idxmax(1).reset\u index(name='TypeName')
你应该把你的建议添加到你的帖子中。我觉得在你的帖子里值得一提@Divakar,但这里的主要思想是使用
.idxmax(1)
-您是第一个…;)链接到我的帖子!但一定要加上!:)
pd.concat((df.Data, df.iloc[:,1:].idxmax(1)),axis=1)
In [42]: df
Out[42]: 
   Data  Type1  Type2  Type3
0    12      1      0      0
1    14      0      1      0
2     3      0      1      0
3    45      0      0      1

In [43]: pd.concat((df.Data, df.iloc[:,1:].idxmax(1)),axis=1)
Out[43]: 
   Data      0
0    12  Type1
1    14  Type2
2     3  Type2
3    45  Type3