大佬教程收集整理的这篇文章主要介绍了根据 Pandas 中的常见列将一个数据帧拆分为多个子数据帧,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
假设数据帧 @H_450_3@df 如下:
@H_450_3@ ISIN Coupon Issue Date maturity Date Jan 18th Jan 19th \ 0 CA135087A610 0.0150 7/30/2012 6/1/2023 103.13 103.14 1 CA135087F254 0.0075 10/19/2015 3/1/2021 100.08 100.08 2 CA135087F585 0.0075 4/11/2016 9/1/2021 100.40 100.40 3 CA135087G328 0.0050 10/11/2016 3/1/2022 100.44 100.43 4 CA135087H490 0.0175 10/6/2017 3/1/2023 103.29 130.29 5 CA135087ZU15 0.0275 8/2/2011 6/1/2022 103.61 103.60 6 CA135087J546 0.0225 10/5/2018 3/1/2024 106.21 106.21 7 CA135087J967 0.0150 4/5/2019 9/1/2024 104.27 104.28 8 CA135087K528 0.0125 10/11/2019 3/1/2025 103.60 103.60 9 CA135087K940 0.0050 4/3/2020 9/1/2025 100.33 100.32 10 CA135087L518 0.0025 10/9/2020 3/1/2026 98.78 98.77 Jan 20th 0 103.10 1 100.08 2 100.39 3 100.41 4 103.25 5 103.57 6 106.17 7 104.25 8 103.59 9 100.30 10 98.76
我需要根据公共列 @H_450_3@ISIN、@H_450_3@Coupon、@H_450_3@Issue Date、@H_450_3@maturity Date 将其拆分为 3 个子数据框。
@H_450_3@common_columns = ['ISIN','Coupon','Issue Date','maturity Date'] df1.columns = common_columns + 'Jan 18th' df2.columns = common_columns + 'Jan 19th' df3.columns = common_columns + 'Jan 20th'
然后将它们保存到一个 excel 文件中,工作表名称为 @H_450_3@Jan 18th、@H_450_3@Jan 19th 和 @H_450_3@Jan 20th。请注意,在实际数据中还有其他日期列 @H_450_3@Jan 21th、@H_450_3@Jan 22th 等。
保存数据帧:
@H_450_3@writer = pd.ExcelWriter('data.xLSX') df1.to_excel(writer,'Jan 18th') df2.to_excel(writer,'Jan 19th') df3.to_excel(writer,'Jan 20th') writer.save()
我怎么能在 Python 中做到这一点?谢谢。
更新:
对于第一张纸的 @H_450_3@ISIN 由 @H_450_3@2021-01-18 代替,1 月 18 日由 @H_450_3@Close Price 代替,第二张纸的 @H_450_3@ISIN 由 @H_450_3@2021-01-19 代替,1 月 19 日由 {{1} },第三张工作表的 @H_450_3@Close Price 被 @H_450_3@ISIN 取代,1 月 20 日被 @H_450_3@2021-01-20 取代。
让我们通过从数据框中删除 @H_450_3@index.difference 来使用 @H_450_3@comm_columns 来获取类似日期的列,然后对于每个类似日期的列使用 @H_450_3@DataFrame.to_excel 和 @H_450_3@pd.ExcelWriter 来创建工作表:
@H_450_3@comm_cols = ['ISIN','Coupon','Issue Date','Maturity Date'] date_cols = df.columns.difference(comm_cols) with pd.ExcelWriter('data.xLSX') as writer: for col in date_cols: sub_df = df[comm_cols + [col]] sub_df.to_excel(writer,sheet_name=col) writer.save()
更新:要在保存工作表时对 @H_450_3@rename 列 @H_450_3@ISIN 使用:
@H_450_3@comm_cols = ['ISIN','Maturity Date'] isin_cols = ['2021-01-18','2021-02-18','2021-02-19'] date_cols = df.columns.difference(comm_cols) with pd.ExcelWriter('data.xLSX') as writer: for col,isin_col in zip(date_cols,isin_cols): sub_df = df[comm_cols + [col]].rename(columns={'ISIN': isin_col}) sub_df.to_excel(writer,sheet_name=col) writer.save()
以上是大佬教程为你收集整理的根据 Pandas 中的常见列将一个数据帧拆分为多个子数据帧全部内容,希望文章能够帮你解决根据 Pandas 中的常见列将一个数据帧拆分为多个子数据帧所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。