[英]how to subtract all pandas dataframe elements with each other easier way?
[英]How to subtract all the date columns from each other (in permutation) and store them in a new pandas DataFrame?
我正在研究 Jupyter,遇到了一种情况,我必须将每列与排列中的每列的差异,然后将它们存储在单独的 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
另外,我想有这种格式的列标题:D1-D2、D1-D3 等。日期的差异必须是正的 integer。 如果有人可以帮助我处理此代码,我将不胜感激。 谢谢!
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.