[英]Pythonic way to create pandas dataframe based on if-else condition for nd-array and 1d-array
I have 3 methods to do some simple calculations.我有 3 种方法来做一些简单的计算。 2 methods are returning
nd-array
and 1 method returns 1d-array
. 2 种方法返回
nd-array
,1 种方法返回1d-array
。 Later, I am creating a pandas dataframe based on the return output from the methods.后来,我根据方法的返回值 output 创建了一个 pandas dataframe。
While I am creating pandas dataframe, I am also calculating std
from the method's result.在创建 pandas dataframe 的同时,我还根据方法的结果计算
std
差。 For nd-array
I need to use axis=0
and axis=1
to calculate std
but for the 1d-array
, I can not use the axis
properties.对于
nd-array
我需要使用axis=0
和axis=1
来计算std
但对于1d-array
,我不能使用axis
属性。
That means I need to use if-else
to calculate std
for different returns from the methods.这意味着我需要使用
if-else
来计算方法的不同返回值的std
差。 Below code is working fine下面的代码工作正常
def main_fn(arr_1):
all_result_summary = []
for method in ["met_1", "met2", "met_3"]:
results: ndarray = np.array(main_fn(list(arr_1), method))
if method == "met_3":
all_result_summary.append(
pd.DataFrame(
{
"Method": method,
"result": results.mean(),
"result_sd_ax_0": results.std(ddof=1),
"result_sd_ax_1": "NA",
},
index=[0],
)
)
else:
all_result_summary.append(
pd.DataFrame(
{
"Method": method,
"result": results.mean(),
"result_sd_ax_0": results.mean(axis=0).std(ddof=1),
"result_sd_ax_1": results.mean(axis=1).std(ddof=1),
},
index=[0],
)
)
summary = pd.concat(all_result_summary, axis=0, ignore_index=True)
return summary
However, I wanted to use a more pythonic way instead of reusing the whole code using if-else
.但是,我想使用更 pythonic 的方式而不是使用
if-else
重用整个代码。 Any other way to optimize the code?还有其他优化代码的方法吗?
How about use x if cond else y
, ternary-style syntax?如何使用
x if cond else y
三元式语法?
def main_fn(arr_1):
all_result_summary = []
for method in ["met_1", "met2", "met_3"]:
results: ndarray = np.array(main_fn(list(arr_1), method))
all_result_summary.append(
pd.DataFrame(
{
"Method": method,
"result": results.mean(),
"result_sd_ax_0": results.std(ddof=1) if method == "met_3" else results.mean(axis=0).std(ddof=1),
"result_sd_ax_1": "NA" if method == "met_3" else results.mean(axis=1).std(ddof=1),
},
index=[0],
)
)
summary = pd.concat(all_result_summary, axis=0, ignore_index=True)
return summary
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.