Python 将数据帧中的所有行合并为除一行以外的其他行
我有一个数据集Python 将数据帧中的所有行合并为除一行以外的其他行,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据集 Item Type market_share Office Supplies 10 Baby Food 20 Vegetables 10 Meat 30 Personal Care 10 Household 20 我想将所有行(除了Baby Food列)合并,以便我的数据集看起来像 Ite
Item Type market_share
Office Supplies 10
Baby Food 20
Vegetables 10
Meat 30
Personal Care 10
Household 20
我想将所有行(除了Baby Food列)合并,以便我的数据集看起来像
Item Type market_share
Others 80
Baby Food 20
我怎样才能做到这一点,基本上把所有的行合并在一起,求和并把它们和其他行一样放在一起。使用-
输出
然后使用值_计数-
TLDR
使用-
输出
然后使用值_计数-
TLDR
您可以使用except功能!=函数为==
您可以使用except功能!=函数为== 按条件或按创建数组或序列,并将缺少的值转换为NaN和聚合和: 按条件或按创建数组或序列,并将缺少的值转换为NaN和聚合和: 您可以使用:
df.groupby(df['Item Type'].eq('Baby Food').map({True:'Baby Food',False:'Others'})).sum()
您可以使用:
df.groupby(df['Item Type'].eq('Baby Food').map({True:'Baby Food',False:'Others'})).sum()
df['market_share_2'].value_counts()
Others 5
Baby Food 1
Name: market_share_2, dtype: int64
pd.Series(np.where(df['Item Type'].values=='Baby Food', 'Baby Food', 'Others')).value_counts()
df[df['market_share'] != 'Baby Food'].sum()
df[df['market_share'] == 'Baby Food'].sum()
s = np.where(df['Item Type'] == 'Baby Food', 'Baby Food', 'Others')
print (s)
['Others' 'Baby Food' 'Others' 'Others' 'Others' 'Others']
s = df['Item Type'].map({'Baby Food':'Baby Food'}).fillna('Others')
print (s)
0 Others
1 Baby Food
2 Others
3 Others
4 Others
5 Others
Name: Item Type, dtype: object
df = df.groupby(s)['market_share'].sum().rename_axis('Item Type').reset_index()
print (df)
Item Type market_share
0 Baby Food 20
1 Others 80
df.groupby(df['Item Type'].eq('Baby Food').map({True:'Baby Food',False:'Others'})).sum()
market_share
Item Type
Baby Food 20
Others 80