在python中将2x16数据帧转换为4 x 4矩阵

2024-10-17 06:19:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将文件转换为邻接矩阵。我需要以允许不同大小的文件填充此矩阵的方式来执行此操作。我当前的工作文件大小为4。这是我的测试文件,我需要的是以一种抽象的方式来处理更大的文件

这是我的测试文件。1-4是布尔值所属的列

1,0
1,0
1,1
1,1
2,0
2,0
2,0
2,1
3,1
3,0
3,0
3,1
4,1
4,1
4,1
4,0

我想了解以下方面的最终结果:

0  0  1  1
0  0  0  1
1  0  0  1
1  1  1  0

下面是生成类似于输入文件的数据帧的代码

# Importing needed libraries
import os.path
from math import sqrt
import numpy as np
import pandas as pd

# changing filepath to a variable name
fileName = "./testAlgorithm.csv"

# opening file, doing file check, converting
# file to dataframe
if os.path.isfile(fileName):
    with open(fileName, "r") as csvfile:
        df = pd.read_csv(fileName, header=None)
else:
    print(f"file{fileName} does not exist")

# method used to count the number of lines
# in data file
def simpleCount(fileName):
    lines = 0
    for line in open(fileName):
        lines += 1
    return sqrt(lines)

# method call for line count.
lineNum = simpleCount(fileName)
print(df)

num = int(simpleCount(fileName))

Tags: 文件csvtopathimportosas方式
2条回答
df = pd.DataFrame({"A":[0,0,1,1,0,0,0,1,1,0,0,1,1,1,1,0]})
    
df.values.reshape(4,4)

如果要使其返回到数据帧

pd.DataFrame(df.values.reshape(4,4), columns=["A", "B", "C", "D"])

您可以尝试:

dummy = pd.DataFrame(columns= [['c1','c2','c3','c4']])
dummy['c1'] = np.array(df['c2'].loc[df['c1'] == 1])
dummy['c2'] = np.array(df['c2'].loc[df['c1'] == 2])
dummy['c3'] = np.array(df['c2'].loc[df['c1'] == 3])
dummy['c4'] = np.array(df['c2'].loc[df['c1'] == 4])

它将为您提供以下信息:

  c1 c2 c3 c4
0  0  0  1  1
1  0  0  0  1
2  1  0  0  1
3  1  1  1  0

相关问题 更多 >