[英]How to iterate for each column name and append it to a table or data frame in python
I want to make a customize correlation table, after a long script this is my final data look like:我想制作一个自定义的相关表,经过一个长脚本后,这是我的最终数据:
ID a ... z
1 76.0 ... 1.033004
2 257.0 ... 0.629641
3 99.0 ... 0.672139
4 52.0 ... 1.007708
5 129.0 ... 1.080922
And this is the script I made to my customize correlation table for a vs all variable这是我为我的自定义相关表制作的脚本,用于 vs 所有变量
pg.pairwise_corr(df_pvt, columns=[['a'], list(df_pvt.columns)], method='pearson')[['X','Y','r']].append
pg.pairwise_corr(df_pvt, columns=[['b'], list(df_pvt.columns)], method='pearson')[['X','Y','r']].append ......... #until variable z
How can I loop or select specific column number without typing variable name 'a' until 'z'?如何在不输入变量名“a”直到“z”的情况下循环或 select 特定列号?
I am new in python.我是 python 的新手。 Thank you in advance先感谢您
import pandas as pd
data = pd.DataFrame({"ID": [1,2,3,4,5], "a": [76.0, 257.0, 99.0,52.0,129.0], "z": [1.033004, 0.629641, 0.672139,1.007708, 1.080922]}, columns=["ID", "a", "z"])
true_columns = []
for index, row in data.iterrows():
true_col_list = [col for col in data.columns[1] if row[col]]
true_columns.append(",".join(true_col_list))
data["Columns"] = true_columns
print(data)
As I'm not allowed to comment yet, I think this is what you're looking for.由于我还不能发表评论,我认为这就是你要找的。 Correct me if I'm wrong.如我错了请纠正我。
for letter in 'abcdefghijklmnopqrstuvwxyz':
pg.pairwise_corr(df_pvt, columns=[letter], list(df_pvt.columns)], method='pearson')[['X','Y','r']].append ....
edit: And I think, if you want to be cool and pythonic (I've seen this in many answers) you could not write out the alphabet yourself but import it with编辑:而且我认为,如果你想变得很酷和 Pythonic(我在很多答案中都看到过),你不能自己写出字母表,而是用
import string
alphabet = string.ascii_lowercase # this equals 'abcdefghijklmnopqrstuvwxyz'
# then iterate over the alphabet
for letter in alphabet:
# do your stuff here something something[letter] something :P
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.