【问题标题】:Python/Pandas: Divide numeric columns from different dataframes based on a common row identifier and unique row-col combinationPython/Pandas:根据共同的行标识符和唯一的行列组合从不同的数据帧中划分数字列
【发布时间】:2023-04-05 14:59:01
【问题描述】:

我想根据共同的唯一行标识符和唯一的行列组合计算两个数据帧的数字列之间的变化率。

这是一个例子。我选择将表格呈现为图像,以便使用颜色来突出两个数据集的特性。也就是说,每个数据框都包含数字和非数字列,并且行和列的顺序可能不同。此外,应进行计算的数字列始终位于“时间”列之后。

df.divide() 方法在这里不起作用,因为行和列的顺序不同。我还在this 线程中看到了最佳答案,但该方法再次不能推广到我的。

【问题讨论】:

  • 两个dfs中是否有对应的列和行?你能以一种方式订购柱子吗? lst=df1.columns.tolist df2[[lst]] 然后也对行进行排序?

标签: python pandas dataframe


【解决方案1】:

如果您的问题本质上是列和行的顺序不正确,则可以通过对列和行重新排序来解决。

#Identifying the columns for which the difference is to be computed. Since #'Time' is the 4th column, we take all columns after that
valCols = list(df.columns)[4:]

#Sorting the datasets so that the rows align
df1 = df1.sort_values('ID')
df2 = df2.sort_values('ID')

#Keeping only the value columns. This also ensures that the columns are in the same order now
df1 = df1[valCols]
df2 = df1[valCols]


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 2012-11-18
    • 1970-01-01
    • 2023-03-21
    • 2021-12-27
    相关资源
    最近更新 更多