首页 > 解决方案 > if 语句加上 concat 结果 pandas

问题描述

我有以下数据框。

东风:

store_id items max percent store_name
1        4     15  26.6    blue
2        4     10  40.0    yellow
3        7     2   350.0   white
4        6     20  30.0    purple

我只想收集大于或等于 40% 的行。结果应该是大于或等于 40% 的列和行的串联。最终结果是:

store_id items max percent store_name
2        4     10  40.0    yellow
3        7     2   350.0   white

和串联应该是:

from store 2 - yellow, 4 items were selected out of 10 possible, with 40.0% achieved
from store 3 - white, 4 items were selected out of 2 possible, with 350.0% achieved

我尝试过的:

df = df[df.percent >= 40]

这将返回我需要的结果,但它不是 if 语句的一部分,并且在为真时连接其结果。

非常感谢任何建议。

标签: pythonpython-3.xpandasdatabase

解决方案


import pandas as pd
import numpy as np

df=pd.read_excel(r"D:\Stack_overflow\test9.xlsx")

df['concat']=np.where(df['percent'] >= 40, "From store "+df['store_id'].astype(str)+
                      " - "+df['store_name']+", "+df['items'].astype(str)+" items were selected out of "+
                      df['max'].astype(str)+" possible, with "+df['percent'].astype(str)+
                      "% achieved",'')

尝试使用 Numpy。在哪里条件


推荐阅读