【问题标题】:creating a dataframe with all combinations of columns and count the rows that are not 0 and NaN创建一个包含所有列组合的数据框,并计算非 0 和 NaN 的行数
【发布时间】:2021-06-04 01:57:29
【问题描述】:
我正在尝试创建一个包含所有列组合的数据框并计算既不是 0 也不是 NaN 的行
我的数据框如下所示:
最终输出如下所示:
| variable_1 |
variable_2 |
count_rows |
| a |
b |
0 |
| b |
c |
1 |
最终输出将包含原始列的所有组合,
'count_rows' 列将遍历原始数据框并计算每个组合的非 0 和 NaN 的行
此外,我想确保允许重复,我的意思是
例如,
| variable_1 |
variable_2 |
count_rows |
| a |
b |
0 |
| b |
a |
0 |
数值和组合都是一样的,只是顺序不同,但我还是想保留。
谢谢
【问题讨论】:
标签:
python
dataframe
combinations
【解决方案1】:
希望我正确理解了您的问题:
def fn(x):
return (
df[[x["0_x"], x["0_y"]]]
.apply(lambda y: (y.notna() & y.ne(0)).all(), axis=1)
.sum()
)
df_out = df.columns.to_frame().merge(df.columns.to_frame(), how="cross")
df_out = df_out[df_out["0_x"] != df_out["0_y"]]
df_out["count_rows"] = df_out.apply(fn, axis=1)
print(df_out.rename(columns={"0_x": "variable_1", "0_y": "variable_2"}))
打印:
variable_1 variable_2 count_rows
1 a b 0
2 a c 1
3 b a 0
5 b c 1
6 c a 1
7 c b 1