【问题标题】:Subtract and divide dataframes with different length, but only show the ones with changed value减去和分割不同长度的数据帧,但只显示值改变的数据帧
【发布时间】:2019-01-25 13:37:46
【问题描述】:

我有两个行长不同、列相似但没有相应排列的数据框。我想从 df1 中减去 df2 ,然后将结果除以 df1 (基本上在最后得到一个百分比)。

Df1

Index       Bircher  Club   Quiche
2019-1-18     16       1     4
2019-1-19     4        9     6
2019-1-28     8        1     6
2019-1-29     4        7     6
2019-1-20     8        1     6

Df2

Index       Bircher  Quiche  Club
2019-1-10     15       1     3
2019-1-18     4        1     1
2019-1-20     4        2     6
2019-1-26     2        1     5
2019-1-25     4        1     2

结果:只有日期 2019-1-18 和 2019-1-20 显示在两个数据框中并且可以使用。那么Df3就用这个数学公式(Df1-DF2)/Df1简单表示

Index       Bircher  Club   Quiche
2019-1-18     75%     0%     75%
2019-1-20     50%    -100%    0%

【问题讨论】:

  • 重命名 df1 和 df2 中的列以区分它们。像 Bircher1、Bircher2 等。内部加入日期的两个数据框。这将为您提供一个只有共同日期的单一数据框。然后只需使用所需的公式创建新的计算列。像 df['Bircher_pct'] = (df['Bircher1'] - df['Bircher2']) / df['Bircher1'] 这样的东西。然后只需将 df 过滤为您想要的 3 pct 列。
  • 无需显式重命名列。请参阅下面的答案,它很简单,可以用于任意数量的列。

标签: python python-3.x pandas dataframe


【解决方案1】:

就在我的脑海中:

# Join the tables to find common rows
merged_df = df1.join(df2, lsuffix='Left', rsuffix='Right', how='inner')

# Calculate the required percentages, column by column
for col in df1.columns:
    merged_df[col] = (merged_df[col + 'Left'] - merged_df[col + 'Right']) / merged_df[col + 'Left']

# Optionally delete all other columns except df1.columns
merged_df = merged_df.loc[:, df1.columns.values]

这假设您要计算所有列的百分比。

【讨论】:

  • 感谢您的建议。考虑到我有 10-20 列,这似乎需要做很多工作。难道没有更简单的方法吗?
  • 您想计算所有 10-20 列的百分比吗?如果是这样,上面的代码将按原样工作。您的确切查询是什么?
  • 我现在明白你的意思了。我尝试了您的代码,但它以某种方式无法正确连接两个数据框,列在那里但没有行。我试图找出问题所在,因为两个数据帧的索引具有相同的格式。
  • 我更改了“how="outer"”,它们都出现了,但python不知何故无法识别来自 df1 的 2019-1-18 和来自 df2 的 2019-1-18 应该粘在一起.. .知道我做错了什么吗?
  • 我必须将 df1 索引转换为日期时间,就像我对 df2 所做的那样,然后它就起作用了。伟大的。非常感谢!
【解决方案2】:

你也可以使用 groupby 和 nth

x = pd.concat([df1,df2]).groupby(level=0)

fg = ((x.nth(0) - x.nth(-1) )/x.nth(0))*100

fg[fg!= 0].dropna()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 2019-11-11
    • 2012-12-15
    • 1970-01-01
    相关资源
    最近更新 更多