矩阵排序分段故障(Matrix sorting segmentation fault)
我需要存储一个矩阵o N个学生有4个字段(数字,1年级,2年级和平均数)。 这可以通过结构来实现,但这不是本练习的目的。 收集数据(
read_data
)后,必须根据平均值(sort_matrix
)对其进行排序。 但是,当插入4个或更多学生时,会发生分段错误。 我一直无法检测到问题的根源。 我错过了什么? 相关代码如下。void read_data(float **mtx, int *size){ float num, grade1, grade2; while( scanf("%f %f %f", &num, &grade1, &grade2)==3 ){ (*size)++; mtx = (float**)realloc(mtx, (*size)*sizeof(float*) ); mtx[*size-1] = (float*)malloc(4*sizeof(float)); mtx[*size-1][0] = num; mtx[*size-1][1] = grade1; mtx[*size-1][2] = grade2; mtx[*size-1][3] = (grade1+grade2)/2; } printf("Done reading\n"); } void sort_matrix(float **mtx, int size){ int i=0, j=0; float *aux = NULL; for(i=0; i<size-1; i++){ for(j = 0; j<size-1-i; j++){ if(mtx[j][3] > mtx[j+1][3]){ aux = mtx[j]; mtx[j] = mtx[j+1]; mtx[j+1]=aux; } } } printf("Done sorting\n"); } int main(void){ float **mtx =(float**)malloc(0); int size=0; read_data(mtx, &size); sort_matrix(mtx, size); print_matrix(mtx, size); return 0; }
编辑:按照下面给出的答案,我发现这个主题被证明是有用的。 结果问题是在没有传递指针地址的情况下改变了mtx的大小。 对于排序功能,不需要传递地址,因为即使mtx数组指向的地址将改变,大小也不会。
I am required to store a matrix o N students with 4 fields (number, grade1, grade2 and average). This could be achieved with a struct, but that is not the purpose of this exercise. Once the data is collected (
read_data
), it must be sorted according to the average (sort_matrix
). However, when more than 4 or more students are inserted, a segmentation fault happens. I have been unable to detect the origin n of the problem. What am I missing? Relevant code is bellow.void read_data(float **mtx, int *size){ float num, grade1, grade2; while( scanf("%f %f %f", &num, &grade1, &grade2)==3 ){ (*size)++; mtx = (float**)realloc(mtx, (*size)*sizeof(float*) ); mtx[*size-1] = (float*)malloc(4*sizeof(float)); mtx[*size-1][0] = num; mtx[*size-1][1] = grade1; mtx[*size-1][2] = grade2; mtx[*size-1][3] = (grade1+grade2)/2; } printf("Done reading\n"); } void sort_matrix(float **mtx, int size){ int i=0, j=0; float *aux = NULL; for(i=0; i<size-1; i++){ for(j = 0; j<size-1-i; j++){ if(mtx[j][3] > mtx[j+1][3]){ aux = mtx[j]; mtx[j] = mtx[j+1]; mtx[j+1]=aux; } } } printf("Done sorting\n"); } int main(void){ float **mtx =(float**)malloc(0); int size=0; read_data(mtx, &size); sort_matrix(mtx, size); print_matrix(mtx, size); return 0; }
EDIT: Following the answers given bellow, I have found this topic which proved to be useful. The problem turned out to be changing the size of mtx without passing the pointer address. For the sorting function, there is no need to pass the address because even though the addresses the mtx array points to will change, the size will not.
原文:https://stackoverflow.com/questions/35439037
最满意答案
附加列对应于数据帧的索引,并在读取CSV文件后进行聚合。 您可以使用此索引以有效的方式对DF进行切片,选择或排序。
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.html
http://pandas.pydata.org/pandas-docs/stable/indexing.html
如果要避免使用此索引,可以在使用函数
pd.to_csv
保存数据pd.to_csv
时将index
标志设置为False
。 此外,您要删除标题并稍后将其聚合,但您可以使用CSV标题来避免此步骤。sample = pd.read_csv('123.csv', dtype={0:str, 1:str, 2:str, 3:float}) sample.to_csv('output.csv', index= False)
希望能帮助到你 :)
The additional column corresponds to the index of the dataframe and is aggregated once you read the CSV file. You can use this index to slice, select or sort your DF in an effective manner.
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.html
http://pandas.pydata.org/pandas-docs/stable/indexing.html
If you want to avoid this index, you can set the
index
flag toFalse
when you save your dataframe with the functionpd.to_csv
. Also, you are removing the header and aggregating it later, but you can use the header of the CSV to avoid this step.sample = pd.read_csv('123.csv', dtype={0:str, 1:str, 2:str, 3:float}) sample.to_csv('output.csv', index= False)
Hope it helps :)
相关问答
更多-
df = pd.DataFrame({'phone_number': ['555-111-2222', '555-111-3333']}) df.phone_number.to_csv('phone_numbers.csv') 如果你不想要索引: df.phone_number.to_csv('phone_numbers.csv', index=False) 如果你想要一个txt文件,只需更改文件名。 结果是一样的。 df.phone_number.to_csv('phone_numbers.txt' ...
-
我会这样做:首先将所有CSV文件(但只有你真正需要的列)读入一个DF,然后制作groupby(['Year','Month','Day']).mean()并将生成的DF保存到CSV文件中: import glob import pandas as pd fmask = 'MonthlyDataSplit/Day/Day*.csv' df = pd.concat((pd.read_csv(f, sep=',', usecols=['Year','Month','Day','AirTemperature']) ...
-
我认为你需要groupby与自定义lambda函数或循环: f = lambda x: x.to_csv(os.getcwd() + "/data_{}.csv".format(x.name.lower()), index=False) df.groupby('CITY').apply(f) for i, x in df.groupby('CITY'): x.to_csv(os.getcwd() + "/data_{}.csv".format(i.lower()), index=False) ...
-
附加列对应于数据帧的索引,并在读取CSV文件后进行聚合。 您可以使用此索引以有效的方式对DF进行切片,选择或排序。 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.html http://pandas.pydata.org/pandas-docs/stable/indexing.html 如果要避免使用此索引,可以在使用函数pd.to_csv保存数据pd.to_csv时将index标志设置为False 。 此外,您要删除标 ...
-
如果你使用dict会更好,你也可以直接将一个url传递给pandas.read_csv 。 所以简化的代码看起来像这样: import pandas as pd periods = ['2012-1st-quarter','2012-2nd-quarter', '2012-3rd-quarter', '2012-4th-quarter'] url = 'https://www.capitalbikeshare.com/assets/files/trip-history-data/{}.csv' d = { ...
-
要从csv文件读取numpy.array ,可以为pandas.read_csv提供一个转换器函数。 码: import ast import numpy as np def from_np_array(array_string): array_string = ','.join(array_string.replace('[ ', '[').split()) return np.array(ast.literal_eval(array_string)) 测试代码: import nump ...
-
你只需要解压缩文件: with zipfile.ZipFile('/path/to/file', 'r') as z: f = z.open('member.csv') table = pd.io.parsers.read_table(f, ...) read_table的filepath_or_buffer参数接受任何类似文件的参数。 You just need to unzip the file: with zipfile.ZipFile('/path/to/file', 'r') a ...
-
正如Jeff所说,这是<= 0.12的错误 (但在0.13中修复)。 In [11]: s = '''A;B 1;2,000 3;4''' In [12]: pd.read_csv(StringIO(s), sep=';', thousands=',') Out[12]: A B 0 1 2000 1 3 4 [2 rows x 2 columns] In [13]: pd.version.version Out[13]: '0.13.0rc1-82-g66934c2' ...
-
当执行csv读取时,pandas数据帧头被移位(pandas data frame headers are shifted over when perfoming csv read)[2022-02-02]
您的csv数据确实看起来很奇怪 - 您有20个列标题,但第一行中有22个条目包含数据。 假设这只是一个复制粘贴错误*,您可以尝试以下方法: df = pd.read_csv(file, skiprows=[1,2], index_col=False) skiprows将跳过两个空行, index_col可能会减轻数据被解释为索引列的影响。 有关csv解析器的所有选项,请参阅http://pandas.pydata.org/pandas-docs/version/0.16.2/generated/panda ... -
你知道系列总是在同一个顺序吗? 如果是这样,我会创建一个MultiIndex,并从中取出。 就像你已经完成的那样阅读Series 。 我将使用此数据框: In [31]: df = pd.DataFrame(np.random.randn(24)) In [32]: df Out[32]: 0 0 -1.642765 1 1.369409 2 -0.732588 3 0.357242 4 -1.259126 5 0.851803 6 -1.582394 7 - ...