Altering a particular column in a CSV with python3 - csv

An example. I have a CSV file laid out as such:
10,20,30,-40,50
20,30,40,-50,60
30,40,50,-60,70
Basically I need to flip the sign of the numbers in a column. Any column. In this example the signs of the 4th and 5th...
10,20,30,40,-50
20,30,40,50,-60
30,40,50,60,-70
And print them to a new file.
I can read in a CSV file, but honestly I have no idea where to go from there. Any help would be greatly appreciated.

Read in the file line by line, and split by the CSV delimiter. The order of the resulting list will be in the order of the columns (ie. splitline[0] is your first csv column, etc.). You can then write that line to a new file and modify the data accordingly. In your case I believe you want the last two value multiplied by negative 1.

Use the csv lib to parse your file:
import csv
with open("in.csv") as f, open("new.csv","w") as tmp:
r = csv.reader(f)
wr = csv.writer(tmp)
# wr.writerow(next(r)) # uncomment if file has header
# (*_ -> all but last two), (a, b -> second last and last value)
# -- == +, -+ == -
wr.writerows(_ + [-int(a), -int(b)] for *_, a, b in r:)
Input:
10,20,30,-40,50
20,30,40,-50,60
30,40,50,-60,70
Output:
10,20,30,40,-50
20,30,40,50,-60
30,40,50,60,-70
If you want the nth columns just change how you unpack:
wr.writerows([a, b, c , -int(d), -int(e)] + _ for a, b, c, d, e,*_ in r:)
^^ ^^
4th 5th
wr.writerows([-int(a),b, -int(c), d, e] + _ for a, b, c, d, e,*_ in r:)
^^ ^^
1st 3rd
If you have 41 columns and want to alter,33,39,40,41:
with open("in.csv") as f, open("out.csv","w") as tmp:
r = csv.reader(f)
wr = csv.writer(tmp)
for *_, t_3, a, b, c, d, e, t_9, ft_0, ft_1 in r:
wr.writerow(_ + [-int(t_3), a, b, c, d, e, -int(t_9), -int(ft_0), -int(ft_1)])

Related

How the variables work on the command Add on MIPS

i have a task which i cannot understand
There are 2 Mips codes which i have to write in C
a)
1.Add f,g,h
b)
Addi f,f,1
Add f,g,h
My question is on (b) Does this mean that f = (f+1) + (g+h) or f = g + h
I don't understand if the first line is overwriten by the second which makes the codes on (a) and (b) the same
Thank you for your time
addi f, f, 1 means f = f + 1, and add f, g, h means f = g + h.
The second instruction will overwrite the value of f produced in the first instruction, so the first instruction has no net effect (other than consuming time and energy) unless the symbol f has been defined to be the same register as g or h.

Maxima add current loop iteration to filename

I have code similar to the one below, where a function with a parameter depending on the loop iteration is plotted after every iteration. I would like to save the plot with the name trigplot_i.ps where i is the iteration number, but don't know how.
I have tried trigplot_"i".ps but didn't work, and have not been able to find how to cast i to a string either.
I'm a beginner so any help is very welcome.
f(x) := sin(x);
g(x) := cos(x);
for i:1 thru 10 do
(plot2d([i*f(x), i*g(x)], [x,-5,5],[legend,"sin(x)","cos(x)"],
[xlabel,"x"],[ylabel,"y"],
[ps_file,"./trigplot_i.ps"],
[gnuplot_preamble,"set key box spacing 1.3 top right"])
);
code after edits gives an error:
f(x) := sin(x);
g(x) := cos(x);
for i:1 thru 10
do block([myfile],
myfile: sconcat("./trigplot_", i, ".ps"),
printf (true, "iteration ~d, myfile = ~a~%", myfile),
plot2d([i*f(x), i*g(x)], [x,-5,5],[legend,"sin(x)","cos(x)"],
[xlabel,"x"],[ylabel,"y"],
[ps_file, myfile],
[gnuplot_preamble,"set key box spacing 1.3 top right"])
);
error:
"declare: argument must be a symbol; found "./trigplot_1.ps
-- an error.
To debug this try: debugmode(true);"
Looks good. To construct a file name, try this: sconcat("./trigplot_", i, ".ps") or also you can try: printf(false, "./trigplot_~d.ps", i). My advice is to make that a separate step in the loop, and then you can use it in the call to plot2d, e.g.:
for i:1 thru 10
do block ([myfile],
myfile: sconcat("./trigplot_", i, ".ps"),
printf (true, "iteration ~d, myfile = ~a~%", i, myfile),
plot2d (<stuff goes here>, [ps_file, myfile], <more stuff>));
EDIT: Fixed a bug in printf (omitted argument i).

Octave: How to sum(A .* B, 3) without expanding A .* B?

Consider the following scenario, for A with size [k, 1, m] and B with size [1, n, m], how can one get the same result as:
C = sum(A .* B, 3);
without expanding
A .* B
Because that takes way too much memory.
Something like the following loop but natively:
C = zeros(k,n);
for idx = 1:m
C += A(:,1,idx) * B(1,:,idx);
end
I guess I could also ask if there's a function like bsxfun with a "reduce"-like behavior?
Something like:
C = bsxfun_accumulate(#(a, b) a * b, A, B);
Note: by native I mean cs/cuda code-paths, or opencl code-path, or x86-sse, or plain x86 instructions. Whatever is available.
You can actually solve your problem by simply reshaping the variables A and B and applying a matrix multiply:
C = reshape(A, [], m)*(reshape(B, [], m).');
Basically, summing the results of m sets of multiplications involving k-by-1 column vectors and 1-by-n row vectors is the equivalent of multiplying a k-by-m matrix of your columns and an m-by-n matrix of your rows.

How to parse tuple, integer, and string in erlang binary?

I want to put ip address, port number and custom content in the binary, do binary matching for integers, but I can't find a way to do it.
Assume the ip address is IP = {192,168,1,1}, port number is PN = 10000, and custom content is Content = <<"{request, {M, F, A}}">>, I can put them all into binary by using Bin = <<list_to_binary(tuple_to_list(IP))/binary, Content/binary, PN/integer>>, the binary result is
<<127,0,0,1,123,114,101,113,117,101,115,116,44,32,123,77,
44,32,70,44,32,65,125,125,16>>
But when I try to do binary matching for the port number(PN), it turns to something else (16), how can I deal with the integer and keep its size to 1 in the binary?
The binary matching is: <<A:4/binary, B:20/binary, C>> = Bin. The result of C is 16, not 10000.
Another problem I want to ask is how to limit the size of packet? Is it possible to limit the packet size without concerning the length of content within it? Compromise or chop it into several pieces?
You will need at least 14 bits to represent the number 10000. One way to do this would be:
Bin = << IPBin/binary, Content/binary, PN:14/integer-unit:1>>.
Which will result in the binary:
<<192,168,1,1,123,114,101,113,117,101,115,116,44,32,123,
77,44,32,70,44,32,65,125,125,156,16:6>>
It can then be matched as follows:
<<A:4/binary, B:20/binary, C:14/integer-unit:1>> = Bin.
Hope this sheds some light on Segments for bit syntax
Note: You will need 2 bytes the represent any port number so PN:16/integer or PN:16/unsigned will be better.
If the port number it's the last part of the binary and the size of everything else it's known, you could use integer_to_binary(PN) and attach this value to the binary.
You would then have to use binary_to_integer(C) for the reverse, ones C is extracted by pattern matching.
3> IP = {192,168,1,1}, PN = 10000, Content = <<"{request, {M, F, A}}">>.
<<"{request, {M, F, A}}">>
4> Encode = fun({A, B, C, D}, PN, Content) -> <<A, B, C, D, PN:16/unsigned, Content/bytes>> end.
#Fun<erl_eval.18.50752066>
5> Decode = fun(<<A, B, C, D, PN:16/unsigned, Content/bytes>>) -> {{A, B, C, D}, PN, Content} end.
#Fun<erl_eval.6.50752066>
6> V = Encode(IP, PN, Content).
<<192,168,1,1,39,16,123,114,101,113,117,101,115,116,44,32,
123,77,44,32,70,44,32,65,125,125>>
7> Decode(V).
{{192,168,1,1},10000,<<"{request, {M, F, A}}">>}

Wanted: Matlab example of an anonymous function returning more than 1 output

I use anonymous functions for simple data value transforms. The anonymous functions are defined with the following syntax
sqr = #(x) x.^2;
I would like to have a simple anonymous function that returns more than one output that can be used as follows . . .
[b,a] = myAnonymousFunc(x);
The Matlab documentation suggests that this is possible, but it does not give an example of the syntax needed to define such a function.
http://www.mathworks.co.uk/help/techdoc/matlab_prog/f4-70115.html#f4-71162
What is the syntax to define such a function [in a single line, like the code example at the top of my post]?
Does this do what you need?
>> f = #(x)deal(x.^2,x.^3);
>> [a,b]=f(3)
a =
9
b =
27
With this example, you need to ensure that you only call f with exactly two output arguments, otherwise it will error.
EDIT
At least with recent versions of MATLAB, you can return only some of the output arguments using the ~ syntax:
>> [a,~]=f(3)
a =
9
>> [~,b]=f(3)
b =
27
If you'd rather not skip outputs using tilde ~ nor output a cell array, you'd only need an auxiliary anonymous function:
deal2 = #(varargin) deal(varargin{1:nargout});
myAnonymousFunc = #(x) deal2(x.^2, x.^3);
then you can obtain just the first output argument or both first and second one:
x = 2;
[b,a] = myAnonymousFunc(x)
b = myAnonymousFunc(x)
results:
b =
4
a =
8
b =
4
You can get multiple outputs from an anonymous function if the function being called returns more than a single output. See this blog post on the MathWorks website for examples of this in action.
There are two ways to get multiple outputs from an anonymous function:
Call a function which returns multiple outputs
From the blog post linked to, they use the eig function like so
fdoubleEig = #(x) eig(2*x)
[e, v] = fdoubleEig(magic(3))
Alternatively you can construct an anonymous function which returns multiple outputs using the deal function.
Here is one I made up:
>>> f = #(x, y, z) deal(2*x, 3*y, 4*z)
>>> [a, b, c] = f(1, 2, 3)
a =
2
b =
6
c =
12
Edit: As noted by Sam Roberts, and in the blog post I link to, you must use the correct number of output arguments when using deal, otherwise an error is thrown. One way around this is to return a cell of results. For example
>>> f = #(x, y, z) {2*x, 3*y, 4*z}
>>> t = f(1, 2, 3)
>>> [a, b, c] = t{:}
a =
2
b =
6
c =
12