在dataframe python上计算列中的特定字符串
我有一个(101×1766)数据帧,我放下了一个样本在dataframe python上计算列中的特定字符串,python,string,pandas,dataframe,count,Python,String,Pandas,Dataframe,Count,我有一个(101×1766)数据帧,我放下了一个样本 Index Id Brand1 Brand2 Brand3 0 1 NaN Good Bad 1 2 Bad NaN NaN 2 3 NaN NaN VeryBad 3 4 Good NaN NaN 4 5 NaN Good VeryGood 5 6 Ve
Index Id Brand1 Brand2 Brand3
0 1 NaN Good Bad
1 2 Bad NaN NaN
2 3 NaN NaN VeryBad
3 4 Good NaN NaN
4 5 NaN Good VeryGood
5 6 VeryBad Good NaN
我想要的是一张这样的桌子
Index VeryBad Bad Good VeryGood
Brand1 1 1 0 0
Brand2 0 0 3 0
Brand3 1 1 0 1
我甚至找不到一个错误的解决办法
因此,希望看到您的帮助选择所有不带first by的列,然后按
value\u counts
计算值,替换不匹配的缺失值,转换为整数,转置和列的最后更改顺序使用重新索引
:
cols = ['VeryBad','Bad','Good','VeryGood']
df = df.iloc[:, 1:].apply(pd.value_counts).fillna(0).astype(int).T.reindex(cols, axis=1)
print (df)
VeryBad Bad Good VeryGood
Brand1 1 1 1 0
Brand2 0 0 3 0
Brand3 1 1 0 1
选择所有不带first by的列,然后按
value\u counts
对值进行计数,替换不匹配的缺失值,转换为整数,对列的更改顺序进行转置和最后使用重新索引
:
cols = ['VeryBad','Bad','Good','VeryGood']
df = df.iloc[:, 1:].apply(pd.value_counts).fillna(0).astype(int).T.reindex(cols, axis=1)
print (df)
VeryBad Bad Good VeryGood
Brand1 1 1 1 0
Brand2 0 0 3 0
Brand3 1 1 0 1
以下是使用和的方法:
[外]
以下是使用和的方法:
[外]
让我们做两个步骤:
melt
+crosstab
s=df.melt(['Id','Index'])
yourdf=pd.crosstab(s.variable,s.value)
yourdf
value Bad Good VeryBad VeryGood
variable
Brand1 1 1 1 0
Brand2 0 3 0 0
Brand3 1 0 1 1
让我们做两个步骤:
melt
+crosstab
s=df.melt(['Id','Index'])
yourdf=pd.crosstab(s.variable,s.value)
yourdf
value Bad Good VeryBad VeryGood
variable
Brand1 1 1 1 0
Brand2 0 3 0 0
Brand3 1 0 1 1
另一种方式是:with+
另一种方式是:with+
还:还:
m=pd.get_dummies(df.set_index('Id').T)
final=m.groupby(m.columns.str.split('_').str[1],axis=1).sum()
Bad Good VeryBad VeryGood
Brand1 1 1 1 0
Brand2 0 3 0 0
Brand3 1 0 1 1