简体   繁体   English

如何相互减去所有日期列(以排列方式)并将它们存储在新的 pandas DataFrame 中?

[英]How to subtract all the date columns from each other (in permutation) and store them in a new pandas DataFrame?

I was working on Jupyter and arrived at a situation where I had to take differences of each column from every other column taken in permutation and then store them in a separate DataFrame.我正在研究 Jupyter,遇到了一种情况,我必须将每列与排列中的每列的差异,然后将它们存储在单独的 DataFrame 中。 I tried using nested loops but got stuck while assigning the values to the DataFrame.我尝试使用嵌套循环,但在将值分配给 DataFrame 时卡住了。

n=0
for i in range(len(list(df.columns))-1):
  for j in range(i+1, len(list(df.columns))-1):
    df1[n] = pd.DataFrame(abs((df.iloc[:,i] - df.iloc[:,j]).dt.days))
    n=n+1
df1

Also, I would like to have column headers in this format: D1-D2, D1-D3, etc. The difference in dates has to be a positive integer.另外,我想有这种格式的列标题:D1-D2、D1-D3 等。日期的差异必须是正的 integer。 I would really appreciate if anyone could help me with this code.如果有人可以帮助我处理此代码,我将不胜感激。 Thanks!谢谢!

A snippet of the DataFrame DataFrame 的片段

import itertools
import pandas as pd

# create a sample dataframe
df = pd.DataFrame(data={"co1":[1,2,3,4], "co22":[4,3,2,1], "co3":[2,3,2,4]})

# iterate over all permutations of size 2 and write to dictionary
newcols = {}
for col1, col2 in itertools.permutations(df.columns, 2):
    newcols["-".join([col1, col2])] = df[col1]-df[col2]

# create dataframe from dict
newdf = pd.DataFrame(newcols)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何更容易地减去所有pandas dataframe元素? - how to subtract all pandas dataframe elements with each other easier way? pandas数据帧中的日期时间不会相互减去 - Datetime in pandas dataframe will not subtract from each other 如何在熊猫中将两列列表相减? - How to subtract two columns of lists from each other in pandas? Pandas 从 dataframe_b 的所有列中减去 dataframe_a 中的每一列,并将结果写入第三个 dataframe - Pandas subtract each column in dataframe_a from all columns of dataframe_b and write result to third dataframe 如何在 Pandas Dataframe 中的“日期”列中的每个元素中减去 n 个季度以创建新列? - How do I subtract n Quarters to each element in a `date` column in a Pandas Dataframe to create a new column? 如何从数据框中的其他列创建新的Pandas数据框列 - How to create a new Pandas dataframe column from other columns in the dataframe 彼此减去两个Pandas DataFrame时间索引? - Subtract two Pandas DataFrame time indexes from each other? 如何从 pandas dataframe 中的当前行中减去前一行以创建一个新列,以每个名称重新启动进程? - How to subtract previous row from current row in a pandas dataframe to create a new column restarting the process with each name? 如何有效地从熊猫数据框中减去每一行? - How to efficiently subtract each row from pandas dataframe? 如何从数字中减去熊猫DataFrame的每一行? - How to subtract each row of a pandas DataFrame from a number?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM