对不同长度的数据帧进行减法和除法,但只显示值发生变化的数据帧

2024-10-03 15:34:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个不同行长的数据帧,类似的列,但没有相应地排列。我想从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显示在两个数据帧中,并且可以使用。然后用这个数学公式(Df1-DF2)/Df1简单地表示Df3

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

Tags: 数据index数学公式百分比df1df2club行长
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()

就在我的头顶上:

# 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]

这假设您要计算所有列的百分比。你知道吗

相关问题 更多 >