- Print a table on a file with tabulate printing one row at a time only having headers for the first row printed
- How to print in one row in python
- How to print individual rows of a pandas dataframe using Python?
- Pandas DataFrame: How to print single row horizontally?
- How to print in a given range in one row?
- How to print DataFrame on single line
- How to print numbers on a new line in python
- 8 Answers 8
- How to print a specific line/row from a text file?
- 3 Answers 3
Print a table on a file with tabulate printing one row at a time only having headers for the first row printed
I am trying to use tabulate to print rows of a pandas DataFrame one at a time on a file. Only the first printing needs the headers, the other rows printed need the same spacing as the first row but no headers printed. Is this achievable with simple tabulate syntax for printing? Here is a snippet code of the idea:
index = 0 with open('texttest.txt', 'w') as f: for state in states[:3]: if index == 0: f.write(tabulate(transition_df, headers='keys', tablefmt='psql', showindex=False )) index += 1 else: f.write(tabulate(transition_df, tablefmt='psql', showindex=False ))
+---------+----------+----------+--------+--------+------+----------+-----------+-----------------+-----------------+--------------------+----------+----------+---------------+---------------+------------------+---------+--------+ | State | Energy | OscStr | Spin | From | To | Coeff | SqCoeff | MO_index_FROM | AtomType_FROM | AtomContrib_FROM | S_FROM | P_FROM | MO_index_TO | AtomType_TO | AtomContrib_TO | S_TO | P_TO | |---------+----------+----------+--------+--------+------+----------+-----------+-----------------+-----------------+--------------------+----------+----------+---------------+---------------+------------------+---------+--------| | 1 | 5.2455 | 0.1416 | 0 | 232 | 244 | -0.23232 | 0.0539726 | 232 | Cl | 0.784 | -0.0012 | 0.7852 | 244 | Cs | 0.6231 | -0.5379 | 1.161 | +---------+----------+----------+--------+--------+------+----------+-----------+-----------------+-----------------+--------------------+----------+----------+---------------+---------------+------------------+---------+--------++---+--------+--------+---+-----+-----+---------+-----------+-----+----+-------+---------+--------+-----+----+--------+--------+--------+ | 2 | 5.3137 | 2.1694 | 0 | 232 | 249 | 0.30159 | 0.0909565 | 232 | Cl | 0.784 | -0.0012 | 0.7852 | 249 | Pb | 0.5911 | 0.0008 | 0.5903 | +---+--------+--------+---+-----+-----+---------+-----------+-----+----+-------+---------+--------+-----+----+--------+--------+--------++---+--------+--------+---+-----+-----+---------+-----------+-----+----+-------+---------+--------+-----+----+--------+--------+--------+ | 3 | 5.3341 | 1.7602 | 0 | 232 | 233 | 0.21276 | 0.0452668 | 232 | Cl | 0.784 | -0.0012 | 0.7852 | 233 | Cs | 0.9384 | 0.7359 | 0.2025 | +---+--------+--------+---+-----+-----+---------+-----------+-----+----+-------+---------+--------+-----+----+--------+--------+--------+
I would like the same spacing as the headers but not print the headers in the file. I have worked out a solution where I generate the dataframe first and then print it, but I want to know if this is possible to do on the fly like I wanted to do here initially.
How to print in one row in python
Rest to do is just to 🙂 edit: Here is example (made based on answer from link) of code that prints rows from previously created dataframe: Solution 1: use the method then transpose with note: This is similar to @JohnE’s answer in that the method is syntactic sugar around . Solution: You need set: context manager has been exposed through the top-level API, allowing you to execute code with given option values.
How to print individual rows of a pandas dataframe using Python?
Here (stackoverflow — How to iterate over rows in a DataFrame in Pandas?) you can find help with iterating over pandas dataframe rows. Rest to do is just to print(row) 🙂
edit:
Here is example (made based on answer from link) of code that prints rows from previously created dataframe:
import pandas as pd inp = [, , ] df = pd.DataFrame(inp) for index, row in df.iterrows(): A = row["c1"] B = row["c2"] C = row["c3"] print('The value of A: <>, B: <>, C: <>'.format(A, B, C))
How do I print a simple Python statement based on Pandas, I have tried putting Train Numbers as keys in a dictionary and then the dates as a values, and then tried printing what I want to print by
Pandas DataFrame: How to print single row horizontally?
use the to_frame method then transpose with T
df = pd.DataFrame([[100,200,300],[400,500,600]]) for index, row in df.iterrows(): print(row.to_frame().T) 0 1 2 0 100 200 300 0 1 2 1 400 500 600
note:
This is similar to @JohnE’s answer in that the method to_frame is syntactic sugar around pd.DataFrame .
In fact if we follow the code
def to_frame(self, name=None): """ Convert Series to DataFrame Parameters ---------- name : object, default None The passed name should substitute for the series name (if it has one). Returns ------- data_frame : DataFrame """ if name is None: df = self._constructor_expanddim(self) else: df = self._constructor_expanddim() return df
Points to _constructor_expanddim
@property def _constructor_expanddim(self): from pandas.core.frame import DataFrame return DataFrame
Which you can see simply returns the callable DataFrame
Use the transpose property:
It seems like there should be a simpler answer to this, but try turning it into another DataFrame with one row.
data = sf = pd.DataFrame(data, index=[0]) print(sf.to_string())
Print pandas row in a single string (jupyter notebook), Use values for convert Series to 1d numpy array : print(df.loc[0].values, df.loc[1].values) [1 3] [2 4]. Or convert to list s:
How to print in a given range in one row?
You can try out with map and give you object and convert into list
n=int(input()) for i in range(n): n2=list(map(int,input().split())) print(n2)
2 input -> (you have to give like this) 1 2 3 [1, 2, 3] input -> (you have to give like this) 2 3 4 [2, 3, 4]
If you want one input to retrieve the values, you don’t need another value holding the number (it would be useful only to make n inputs)
values = list(map(int, input().split())) print(values)
1 2 3 4 5 6 7 [1, 2, 3, 4, 5, 6, 7] 1 2 3 4 5 6 7 8 9 [1, 2, 3, 4, 5, 6, 7, 8, 9]
u = int(input("Enter number of inputs: ")) for e in range(1, u+1): print(e, end=" ")
Here, I would use the «end» keyword so that all numbers in the range are returned on the same line. (:
How can I pull a single row from CSV file?, Are you looking to print a specific row, or just the first row? Does the CSV file have a header row? If so, do you want to print that as well?
How to print DataFrame on single line
pd.set_option('expand_frame_repr', False)
option_context context manager has been exposed through the top-level API, allowing you to execute code with given option values. Option values are restored automatically when you exit the with block:
#temporaly set expand_frame_repr with pd.option_context('expand_frame_repr', False): print (df)
Python — Pandas — Print a single row in the same format as .head(), Hi you can do it like this df.head(202).tail(1). I hope it will help you. OR. And also you can use df[206:207]. OR. df.iloc[[207]].
How to print numbers on a new line in python
A program accepts a number of inputs, for instance numbers or integers, how do you print each and every one of them on a new line. Eg. I enter this 2,4,5,2,38. The program should display each one on a new line as this.
Item = input ("Enter your number") #user enters the following numbers 5,2,6,3,2 #print out each number on a new line # output 5 2 6 3 2
@ronakg well I tried storing all the numbers in one variable and tried to print them out,but it seem to only print the last number i imputed.
8 Answers 8
All you need is a simple for loop that iterates over the input and prints it
data = raw_input('enter ints').split(',') for n in data: if n.isdigit(): print n
Note if you are using Pyhon 3.x, you need to use input instead of raw_input
The first row assigns user input data to data variable and splits items by space. (You can change this tow ‘,’ instead) The for loop does iteration on every item in that list and checks if it is a digit. Because the list elements are strings, we can use isdigit() method of string to test it.
>>> '5'.isdigit() True >>> '12398'.isdigit() True
If you want to do it in another way, maybe using ‘\n’.join(data) method, which will join the list elements and join them with ‘\n’.
>>> inpu = raw_input('enter ints\n').split(',') >>> inpu = [c.strip() for c in inpu] >>> print '\n'.join(inpu) 1 2 3 4
This is actually the better way to go, as it is simpler than a for loop.
How to print a specific line/row from a text file?
i want to read the last value from the fourth column if i type the persons number and the number 1 to show the value. Unfortunately, I can’t get any further from here. How can i do this?
data_next = [] for data in open("my_data.txt"): liste = data.split(",") number = int(liste[0]) name = liste[1] sex = liste[2] value = liste[3] data_next.append(number) print(f" [] ") which_person = int(input("WHICH PERSON?: ")) if which_person in data_next: print("Do you want to know the value? Press 1 for YES or 2 for NO") next_input = int(input("YOUR INPUT: ")) if next_input == 1: print(value) elif next_input == 2: print("THX")
3 Answers 3
You need to save the values as well in the structure, a dict is very well suited for that : number as key, values as value
data_next = <> with open("my_data.txt") as fic: for data in fic: liste = data.split(",") number = int(liste[0]) data_next[number] = liste[1:] print(f" [] ")
Then use the dict, to access the values
if which_person in data_next: print("Do you want to know the value? Press 1 for YES or 2 for NO") next_input = int(input("YOUR INPUT: ")) if next_input == 1: print(data_next[which_person][2]) elif next_input == 2: print("THX")
With regex you can handle nicely the comma+space delimiter
data_next = <> with open("my_data.txt") as fic: for data in fic: nb, *others = re.fullmatch(r"(\d+),\s*([^,]+),\s*(\w+),\s*(\d+.?\d*)", data).groups() data_next[nb] = others print(f" [] ") which_person = input("WHICH PERSON?: ")
Thx I’ve got it. But I Have a another question. I have implmented a next_input == 3 . If this happens I can give a number and it will adds the current value. How can I save the changes in the same .txt file?
The for-loop at the beginning of your code succeeds in placing all of the ‘values’ from the text file into one list.
data_next = ["1000.0", "790.0", "400.0"]
However, that list isn’t useful for what you are trying to do below, which is to take input for one of the names from the data file and print the corresponding number. What you want for this is a dictionary, which links from one value to another. To achieve this, use the following code:
# set data_next to an empty dictionary data_next = <> for data in open("my_data.txt"): liste = data.split(",") number = int(liste[0]) name = liste[1] sex = liste[2] value = liste[3] # set the current number equal to the current value in the dictionary data_next[number] = value print(f" [] ") which_person = int(input("WHICH PERSON?: ")) # data_next.keys() will return an iterable of all of the id numbers in the dictionary if which_person in data_next.keys(): print("Do you want to know the value? Press 1 for YES or 2 for NO") next_input = int(input("YOUR INPUT: ")) if next_input == 1: # data_next[which_person] will return the value in the dictionary assigned to the number which_person print(data_next[which_person]) elif next_input == 2: print("THX")
Another thing: This code will perform slightly differently than you expect because of how the file is formatted When you split each line by «,».
"1, Max Mustermann, Male, 1000.0".split(",") == ["1", " Max Mustermann", " Male", " 1000.0"]
As you can see, the spaces after each comma are included with the next value. To fix this, change the split statement to split(«, «) instead of split(«,») OR remove the spaces after the commas in the file.