python - 选择数据框
问题描述
我有这样的数据框:
Tahun Jan Feb Mar Apr Mei Jun Jul Ags Sep Okt Nov Des
0 2020 0.39 0.28 0.10 0.08 0.07 0.18 -0.10 -0.05 -0.05 0.07 0.28 0.45
1 2021 0.26 0.10 0.08 0.13 0.32 -0.16 0.08 0.00 0.00 0.00 0.00 0.00
我想选择 != 0.00 的当前值,该值是 2021 年 7 月的值。因此,预期的输出是数据框:
Tahun Month Value
2021 Jul 0.08
我做了:
dfs = df.where(df != 0.00).stack()
r, c = dfs.last_valid_index()
x = dfs.loc[r, [c, 'Tahun']]
输出如下:
1 Tahun 2021.00
Jul 0.08
dtype: float64
如何转换?谢谢
解决方案
您可以将您的解决方案与 set Tahun
to index
first 一起使用:
df = df.set_index('Tahun').rename_axis('Month', axis=1)
s = df.where(df != 0.00).stack()
df2 = s.loc[[s.last_valid_index()]].reset_index(name='Value')
print (df2)
Tahun Month Value
0 2021 Jul 0.08
或使用 的解决方案melt
,但为了正确排序,将Month
s 转换为有序分类:
df = df.melt(id_vars=["Tahun"],
var_name="Month",
value_name="Value")
cats = ['Jan', 'Feb', 'Mar', 'Apr','Mei', 'Jun', 'Jul', 'Ags', 'Sep', 'Okt', 'Nov', 'Des']
df['Month'] = pd.Categorical(df['Month'], ordered=True, categories=cats)
df = df.sort_values(['Tahun','Month'])
df2 = df[df['Value'].ne(0)].tail(1)
print (df2)
Tahun Month Value
13 2021 Jul 0.08
推荐阅读
- java - 如何修复:java.lang.ClassNotFoundException:gradle gatlingRun 任务的 BasicSimulation?
- python - 如何使用 pyspark 将 spark DataFrame 保存回 Google BigQuery 项目?
- javascript - 使用基于语音的命令无法从 firebase 数据库或 Dialogflow 获取数据的 Google 助手出错
- python - GenSim 中具有固定 Eta 的引导式 LDA
- sql - 我想用上个月的数据填充列中的空白字段
- python - 使用 load_learner 加载 export.pkl 模型时出现属性错误。没有独角兽的作品
- c# - 将 C# 项目导出为 .EXE 文件
- java - 我正在尝试用mysql配置liferay,但我有一个oracle给我这个错误的结果
- spring-boot - 带有配置文件 jdbc 的 spring 云配置与旧版 tomcat 和其他具有 dev 配置文件的应用程序一起部署
- python - 如何在考虑行子集的同时遍历 Pandas DataFrame