Post procesamiento de datos en un archivo csv usando scriptTengo una carpeta con varios archivos csv que tienen una estructura de datos similar cuyos datos necesito para procesar y almacenar los resultados en un nuevo archivo.
Cada archivo csv tiene 2 columnas, necesito procesar los datos en la segunda columna de la siguiente manera:
- Nombra la segunda columna como artículos
- Realice la siguiente operación en todas las filas creando una nueva columna x con la siguiente fórmula: 36 + -19.5 *: elementos + 49.99 *: artículos *: artículos *: artículos
- Realice la siguiente operación en todas las filas de la columna x creando la columna y:
Media (: x [Índice (Fila () - 4, Fila ())]) - Encuentra la media y el máximo de la columna y
- Almacene el valor mean y max en el archivo y repita el mismo procedimiento para otros archivos también Ejemplo de archivo csv pfa.
Estoy tratando algo como abajo, pero ya que solo soy un principiante, así que podría ayudar
// Read all the file names
files = Files In Directory( "C:\Users\MyUserName\Documents\My Data\" );
X = N Items( files );
Y = "C:\Users\MyUserName\Documents\My Data\";
//stores the mean and max value of each file
dt = New Table( "My data file");
For( i = 1, i < X, i++,
//open jmp files for each csv files.
dt1 = Open(
Y || files[i],
//Code to add column name and the find mean and max
);
dt1 << Set Name( files[i] );
//I concatenated all the files in one jmp file and close it each time.
dt << Concatenate( Data Table( dt1 ), "Append to first table" );
Close( dt1 );
);
Re: Post procesamiento de datos en un archivo csv usando scriptEsto da una buena base para resolver el problema.Re: Post procesamiento de datos en un archivo csv usando scriptGracias por optimizar y resolver el error, muy útil !!Re: Post procesamiento de datos en un archivo csv usando scriptEstás tan cerca .......
Parecía que se estaba moviendo hacia una lista, se leen las estadísticas que desea después de cada csv. Su sintaxis para hacer eso es incorrecta, y en mi opinión, no tiene que poner los valores en una lista, sino más bien, ponerlos directamente en su tabla de resumen. Además, al calcular las estadísticas en una columna, debe utilizar la forma de columna de la estadística (es decir, Col Max ()). Finalmente, si una vez que haya terminado de procesar el archivo csv, no tiene la necesidad de que continúe dando vueltas, simplemente puede cerrarlo. Agregué una línea que haría eso, pero lo comenté. Solo quita la // si quieres que tenga efecto.
Names Default To Here( 1 );
// Use a function to open a .CSV file: Given the path to such a file, returns a reference to the resulting table
openMyCSV = Function( {path2File},
{Default Local},
dt = Open(
path2File,
columns(
New Column( "column 1", Numeric, "Continuous", Format( "Best", 12 ) ),
New Column( "items", Numeric, "Continuous", Format( "Best", 12 ) )
),
Import Settings(
End Of Line( CRLF, CR, LF ),
End Of Field( Comma, CSV( 0 ) ),
Strip Quotes( 1 ),
Use Apostrophe as Quotation Mark( 0 ),
Use Regional Settings( 0 ),
Scan Whole File( 1 ),
Treat empty columns as numeric( 0 ),
CompressNumericColumns( 0 ),
CompressCharacterColumns( 0 ),
CompressAllowListCheck( 0 ),
Labels( 0 ),
Column Names Start( 1 ),
Data Starts( 1 ),
Lines To Read( "All" ),
Year Rule( "20xx" )
)
)
);
// Start your summary table
dt = New Table( "My summary file" );
dt << New Column( "MovAvgMean", Numeric );
dt << New Column( "MovAvgMax", Numeric );
// Put all the .csv files to process into a list
dir = Pick Directory(
"Directory containing your csv files",
"C:\Users\shilpajo\Documents\PV\KT\LIMC\iccMax\DIADEM\JMP\files\"
);
files = Files In Directory( dir );
For( f = N Items( files ), f >= 1, f--,
If( !Ends With( Uppercase( files[f] ), ".CSV" ),
Remove From( files, f )
)
);
// Process each file - Incomplete!
For( f = 1, f <= N Items( files ), f++,
thisTable = openMyCSV( dir || files[f] );
thisTable << New Column( "x",
Numeric,
Continuous,
Formula( 36 + -19.5 * :items + 49.99 * :items * :items * :items )
);
thisTable << New Column( "av", Numeric, Continuous, Formula( Mean( :x[Index( Row() - 9, Row() )] ) ) );
// This will insure that all formula processing is complet before the next statement is run
thisTable << run formulas;
// Add the summary statistics to the summary table
dt << Add Rows( 1 );
dt:MovAvgMean[N Rows( dt )] = Col Mean( thisTable:av );
dt:MovAvgMax[N Rows( dt )] = Col Max( thisTable:av );
// Close( thisTable, nosave );
);
Re: Post procesamiento de datos en un archivo csv usando scriptEste código me fue muy útil para comenzar. El siguiente código funciona perfectamente. Al almacenar me refiero a que necesito crear una tabla de resumen que contenga la media y la máxima de la columna av de cada archivo csv, ¿cómo puedo hacer eso?
Probé el uso de: dt << Agregar filas ({MovAvgMean = Media (: av) , MovAvgMax = Max (: av)}); // lista única
Pero no funciona ya que me sale un error.
Nombre no resuelto: av {1} en acceso o evaluación de 'av',: av / * ### * /
NamesDefaultToHere(1);
// Use a function to open a .CSV file: Given the path to such a file, returns a reference to the resulting table
openMyCSV =
function({path2File}, {Default Local},
dt = Open(
path2File,
columns(
New Column( "column 1", Numeric, "Continuous", Format( "Best", 12 ) ),
New Column( "items", Numeric, "Continuous", Format( "Best", 12 ) )
),
Import Settings(
End Of Line( CRLF, CR, LF ),
End Of Field( Comma, CSV( 0 ) ),
Strip Quotes( 1 ),
Use Apostrophe as Quotation Mark( 0 ),
Use Regional Settings( 0 ),
Scan Whole File( 1 ),
Treat empty columns as numeric( 0 ),
CompressNumericColumns( 0 ),
CompressCharacterColumns( 0 ),
CompressAllowListCheck( 0 ),
Labels( 0 ),
Column Names Start( 1 ),
Data Starts( 1 ),
Lines To Read( "All" ),
Year Rule( "20xx" )
)
)
);
dt = New Table( "My data file");
dt << New Column( "MovAvgMean", Numeric );
dt << New Column( "MovAvgMax", Numeric );
// Put all the .csv files to process into a list
dir = pickDirectory("Directory containing your csv files", "$DESKTOP");
files = filesInDirectory(dir);
for(f = NItems(files), f>=1, f--, if(!endsWith(uppercase(files[f]), ".CSV"), removeFrom(files, f)));
// Process each file - Incomplete!
for(f = 1, f <= NItems(files), f++,
thisTable = openMyCSV(dir||files[f]);
thisTable << newColumn("x", Numeric, Continuous, Formula(36 + -19.5 * :items + 49.99 *:items* :items* :items));
thisTable << newColumn("av", Numeric, Continuous, Formula(Mean( :x[Index( Row() - 9, Row() )] )));
dt << Add Rows( {MovAvgMean =Mean(:av), MovAvgMax = Max(:av)} ); // single list
);
// Make the summary table
Re: Post procesamiento de datos en un archivo csv usando scriptSi está comenzando, debe tomar esto en etapas, entendiendo cómo funciona cada parte. Use 'Ayuda> Índice de secuencias de comandos' y 'Ayuda> Libros> Guía de secuencias de comandos' para buscar información.
El código que aparece a continuación debería ayudarlo a comenzar, y es posible que pueda hacer el resto. Tendrá que ser más precisos acerca de lo que quiere decir con "almacenar el valor". . . en el archivo '.
NamesDefaultToHere(1);
// Use a function to open a .CSV file: Given the path to such a file, returns a reference to the resulting table
openMyCSV =
function({path2File}, {Default Local},
dt = Open(
path2File,
columns(
New Column( "column 1", Numeric, "Continuous", Format( "Best", 12 ) ),
New Column( "items", Numeric, "Continuous", Format( "Best", 12 ) )
),
Import Settings(
End Of Line( CRLF, CR, LF ),
End Of Field( Comma, CSV( 0 ) ),
Strip Quotes( 1 ),
Use Apostrophe as Quotation Mark( 0 ),
Use Regional Settings( 0 ),
Scan Whole File( 1 ),
Treat empty columns as numeric( 0 ),
CompressNumericColumns( 0 ),
CompressCharacterColumns( 0 ),
CompressAllowListCheck( 0 ),
Labels( 0 ),
Column Names Start( 1 ),
Data Starts( 1 ),
Lines To Read( "All" ),
Year Rule( "20xx" )
)
)
);
// Put all the .csv files to process into a list
dir = pickDirectory("Directory containing your csv files", "$DESKTOP");
files = filesInDirectory(dir);
for(f = NItems(files), f>=1, f--, if(!endsWith(uppercase(files[f]), ".CSV"), removeFrom(files, f)));
// Process each file - Incomplete!
for(f = 1, f <= NItems(files), f++,
thisTable = openMyCSV(dir||files[f]);
thisTable << newColumn("x", Numeric, Continuous, Formula(36 + -19.5 * :items + 49.99 *:items* :items* :items));
);