gpt4 book ai didi

python - Pandas :每次迭代迭代两列

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:47 26 4
gpt4 key购买 nike

有谁知道如何对每次迭代包含两列的 pandas Dataframe 进行迭代?

说我有

   a            b             c            d
5.1 3.5 1.4 0.2
4.9 3.0 1.4 0.2
4.7 3.2 1.3 0.2
4.6 3.1 1.5 0.2
5.0 3.6 1.4 0.2
5.4 3.9 1.7 0.4

有点像

for x, y in ...:
correlation of x and y

所以输出将是

corr_ab     corr_bc     corr_cd
0.1 0.3 -0.4

最佳答案

您可以使用带有元组索引的zip,使用Series.corr 创建一个元素列表的字典。和 f-string 用于列名并传递给 DataFrame 构造函数:

L = {f'corr_{col1}{col2}': [df[col1].corr(df[col2])] 
for col1, col2 in zip(df.columns, df.columns[1:])}

df = pd.DataFrame(L)
print (df)
corr_ab corr_bc corr_cd
0 0.860108 0.61333 0.888523

关于python - Pandas :每次迭代迭代两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57039114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com