小编Mai*_*and的帖子

Python Dataframe Groupby Mean 和 STD

我知道如何通过平均值或标准计算分组。但现在我想一次计算两者。我的代码:

df = 
   a      b      c      d
0  Apple  3      5      7
1  Banana 4      4      8
2  Cherry 7      1      3
3  Apple  3      4      7

xdf = df.groupby('a').agg([np.mean(),np.std()])
Run Code Online (Sandbox Code Playgroud)

当前输出:

TypeError: _mean_dispatcher() missing 1 required positional argument: 'a'
Run Code Online (Sandbox Code Playgroud)

python numpy mean dataframe pandas-groupby

2
推荐指数
1
解决办法
56
查看次数

Python 重塑具有奇数个元素的列表

我有一个包含奇数个元素的列表。我想把它转换成特定的尺寸。

我的代码:

alist = ['a','b','c']
cols= 2
rows = int(len(alist)/cols)+1 # 2
anarray = np.array(alist.extend([np.nan]*((rows*cols)-len(months_list)))).reshape(rows,cols)
Run Code Online (Sandbox Code Playgroud)

当前输出:

ValueError: cannot reshape array of size 1 into shape (2,2)
Run Code Online (Sandbox Code Playgroud)

预期输出:

anarray  = [['a','b'],['c',nan]]
Run Code Online (Sandbox Code Playgroud)

python arrays numpy list

1
推荐指数
1
解决办法
834
查看次数

基于 Python 数据框日期时间的 if 和 else 条件

我有一个数据时间数据框。我想将它与参考日期进行比较,并指定before它小于或after大于。
我的代码:

df = pd.DataFrame({'A':np.arange(1.0,9.0)},index=pd.date_range(start='2020-05-04 08:00:00', freq='1d', periods=8))
df=     
                       A
2020-05-04 08:00:00  1.0
2020-05-05 08:00:00  2.0
2020-05-06 08:00:00  3.0
2020-05-07 08:00:00  4.0
2020-05-08 08:00:00  5.0
2020-05-09 08:00:00  6.0
2020-05-10 08:00:00  7.0
2020-05-11 08:00:00  8.0

ref_date = '2020-05-08'
Run Code Online (Sandbox Code Playgroud)

预期答案

df=     
                       A    Condi.
2020-05-04 08:00:00  1.0    Before
2020-05-05 08:00:00  2.0    Before
2020-05-06 08:00:00  3.0    Before
2020-05-07 08:00:00  4.0    Before
2020-05-08 08:00:00  5.0    After
2020-05-09 08:00:00  6.0    After
2020-05-10 08:00:00  7.0    After
2020-05-11 08:00:00  8.0    After
Run Code Online (Sandbox Code Playgroud)

我的解决方案:

df['Cond.'] = …
Run Code Online (Sandbox Code Playgroud)

python datetime dataframe pandas

1
推荐指数
1
解决办法
33
查看次数

交替组合两个列表

我正在做一个简单的列表理解:以替代顺序组合两个列表并制作另一个列表。

big_list = [i,j for i,j in zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28'])]
Run Code Online (Sandbox Code Playgroud)

预期输出:

['2022-01-01','2022-01-31','2022-02-01','2022-02-28']
Run Code Online (Sandbox Code Playgroud)

当前输出:

Cell In[35], line 1
    [i,j for i,j in zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28'])]
     ^
SyntaxError: did you forget parentheses around the comprehension target?
Run Code Online (Sandbox Code Playgroud)

python list-comprehension list python-3.x python-zip

1
推荐指数
1
解决办法
149
查看次数