我想将具有特定前缀的列加载到单独的 DataFrame 中。
我想要的列有特定的前缀,即
A_1 A_2 B_1 B_2 C_1 C_2
1 0 0 0 0 0
1 0 0 1 1 1
0 1 1 1 1 0
我有所有前缀的列表:
prefixes = ["A", "B", "C"]
我想做这样的事情:
for prefix in prefixes:
f"df_{prefix}" = pd.read_csv("my_file.csv",
usecols=[f"{prefix}_1,
f"{prefix}_2,
f"{prefix}_3,])
因此每个 DataFrame 的名称中都有前缀,但我不太确定执行此操作的最佳方法或所需的语法。
最佳答案
您可以尝试使用不同的方法。加载完整的 csv 一次。通过删除与您的前缀不匹配的列来创建三个 df。
x = pd.read_csv("my_file.csv")
notA = [c for c in x.columns if 'A' not in c]
notB = [c for c in x.columns if 'B' not in c]
notC = [c for c in x.columns if 'C' not in c]
a = x.drop(notA,1)
b = x.drop(notB,1)
c = x.drop(notC,1)
关于python - 根据前缀将列加载到多个 DataFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53591735/