Python 根据条件组织dataframe中的列

Python 根据条件组织dataframe中的列,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个这样的产品数据框架 category,number of products Apple pc,3 Lenovo pc,7 HP pc,4 Apple chargher,6 Lenovo charger,9 category,number of products pc,14 charger,15 我想对类别进行分组,如果它们包含相同的字符串(例如pc或充电器),并将它们发送到另一个数据帧,如下图所示 category,number of products Apple pc,3 Leno

我有一个这样的产品数据框架

category,number of products
Apple pc,3
Lenovo pc,7
HP pc,4
Apple chargher,6
Lenovo charger,9
category,number of products
pc,14
charger,15
我想对类别进行分组,如果它们包含相同的字符串(例如pc或充电器),并将它们发送到另一个数据帧,如下图所示

category,number of products
Apple pc,3
Lenovo pc,7
HP pc,4
Apple chargher,6
Lenovo charger,9
category,number of products
pc,14
charger,15
我可以用熊猫来做这件事吗?

你可以试试:

作为pd进口熊猫

data={'category':['Apple pc','Lenovo pc','HP pc','Apple charger','Lenovo charger'],
      'number of products':[3,7,4,6,9]}

df = pd.DataFrame(data)
new = df["category"].str.split(" ", n = 1, expand = True)
df['brand']=new[0]
df['kind']=new[1]
print(df)
df:

然后进行分组:

print(df.groupby('kind')['number of products'].sum().sort_values())
结果:

kind
pc         14
charger    15
Name: number of products, dtype: int64

您可以在一行代码中执行此操作

    In [174]: df
    Out[174]:
             category  number of products
    0        Apple pc                   3
    1       Lenovo pc                   7
    2           HP pc                   4
    3  Apple chargher                   6
    4  Lenovo charger                   9
    
    In [175]: df.groupby([df["category"].str.split().str[-1]])["number of products"].sum()
    Out[175]:
    category
    charger      9
    chargher     6
    pc          14
    Name: number of products, dtype: int64
   
    In [177]: pd.DataFrame(df.groupby([df["category"].str.split().str[-1]])["number of products"].sum()).reset_index()
    Out[177]:
   category  number of products
0   charger                   9
1  chargher                   6
2        pc                  14

试试这个

 df['Category'] = df["Category"].apply(lambda x: x.split(" ")[1])
 df1 = df.groupby("Category").sum()
输出

 Category   num_of_product
 charger    15
 pc         14


问题在于OP表示如果它们包含相同的字符串,那么可能在拆分时字符串不会位于最后一个索引处。OP没有这样说看看问题。它说的很准确:如果它们包含相同的字符串。OP说
,如果它们包含相同的字符串(例如pc或充电器),我想对类别进行分组,并将它们发送到另一个类似这样的数据帧
——这里他给出了示例,但他没有明确说明。同意你在alsoOk上的观点,idk,对我来说很清楚,但根据公认的答案,我似乎误解了这个问题。问题是OP说如果它们包含相同的字符串,那么可能,拆分时,字符串不会位于最后一个索引处。在我的数据库中,重复的字符串始终位于第一位,因此我没有问题
New_df=pd.DataFrame(df['Name'].str.split(' ',1).tolist(),columns=['Company','type'])

New_df['Units']=data['Unit']

print(New_df)
x = New_df[New_df['type']=='pc']['Units'].sum()

y = New_df[New_df['type']=='charger']['Units'].sum()

dfx = pd.DataFrame({'category':['pc','charger'],'number of products':[x,y]}) #creating a new dataframe

print(dfx)