【发布时间】:2019-12-17 06:36:55
【问题描述】:
我是 python and pandas 的新手。现在,在这里,我有来自三个不同数据框列的 value_counts,我已使用以下内容将其转换为数据框,
df1 = pd.DataFrame()
df1 = first_count.rename_axis('PredictedFeature').reset_index(name='counts') ,In the same way I got three dataframes ,
df1 =
predictedFeature counts
100 100
200 300
2200 150
0 11
10 15
dF2 =
predictedFeature counts
100 200
200 310
2100 150
2200 123
160 4
0 100
df3 =
predictedFeature counts
100 112
200 190
3600 89
156 2
2200 180
0 10
现在,为了合并这些数据框,我尝试了
df_final = [df1, df2, df3]
df_final_percentage = reduce(lambda left, right: pd.merge(left, right, on='PredictedFeature'), df_final)
完成此操作后,它正在创建数据框,但它仅采用常见的 predictFeatures 值。
所以,我得到了最终的数据框,例如,
predictedFeature counts_x counts_y counts
100 100 200 112
200 300 310 190
2200 150 123 180
如何从这三个中获取所有值,如果数据框不存在 predictFeature 则该位置应为 0。
输出会像,
PredictedFeature counts_x counts_y counts
100 100 200 112
200 300 310 190
2200 150 123 180
2100 0 150 0
160 0 4 0
3600 0 0 89
156 0 0 2
谁能帮我解决这个问题?
一件事是在划分的同时
df["counts_y"] = df["counts_y"] * 100 / df["counts_x"]
df["counts_per"] = df["counts"] * 100 / df["counts_x"]
值中的 0 会影响百分比计算吗?
cols = ["PredictedFeature", "counts_per", "counts_y"]
df_percentage.to_csv('data.csv', columns=cols)
用于创建百分比 csv。
【问题讨论】:
-
将
how='left'放入pd.merge()并用0 填充nan?
标签: python pandas numpy dataframe