r/learnpython • • Jul 25 '24

pandas.readcsv() cant read values starts with 't'

I have txt file that looks like that:

a   1   A1
b   t   B21
c   t3  t3
d   44  n4
e   55  t5

but when I'm trying to read it into data frame with pd.readcsv(), the values that start with 't' interpreted as nan and all values to the end of the line. what can I do?

my code:

import pandas as pd
df = pd.read_csv('file.txt', sep='\t', comment='t', header=None)
df
   0     1    2
0  a   1.0   A1
1  b   NaN  NaN
2  c   NaN  NaN
3  d  44.0   n4
4  e  55.0  NaN

How can I make it read all the values in the txt file to the dataframe? Thanks!

1 Upvotes

13 comments sorted by

41

u/roelschroeven Jul 25 '24

What is the purpose of comment='t'?

69

u/thuiop1 Jul 25 '24

Of course it can't, you are literally telling it that anything following a t is a comment.

4

u/Alwaysragestillplay Jul 25 '24

Wild. All that's needed to solve this problem is the ability to read English. This person hasn't even tried to read "their" code before posting. 

31

u/Plank_With_A_Nail_In Jul 25 '24

Lol this is what happens when you copy someone else's code without trying to understand it.

df = pd.read_csv('file.txt', sep='\t', comment=**'t'**, header=None)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

Comment

Character indicating that the remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as skip_blank_lines=True), fully commented lines are ignored by the parameter header but not by skiprows. For example, if comment='#', parsing #empty\na,b,c\n1,2,3 with header=0 will result in 'a,b,c' being treated as the header.

Its why B21 is also not read in

Your data doesn't have any comments and the comment parameter is optional.

8

u/SiriusLeeSam Jul 25 '24

Was this code AI generated?

1

u/MiniMages Jul 25 '24
df = pd.read_csv('file.txt', sep='\s+', header=None)

1

u/Allmyownviews1 Jul 25 '24

I appreciate this.. just need to prepare metadata columns with such a comment character and life is much easier!

1

u/sinterkaastosti23 Jul 26 '24 edited Jul 26 '24
df.map(lambda x: np.nan if isinstance(x, str) and x.startswith('t') else x)

e: wait what ur asking for it NOT to happen?? just remove the comment parameter lol

-28

u/sinterkaastosti23 Jul 25 '24

not sure if that's possible with just read_csv

i suggest reading in your csv, loop over your columns, pl.col(colname).str.startswith('t').then(None).else(pl.col(colname)).alias(colname).

something along those lines

2

u/NYX_T_RYX Jul 25 '24

They're using pandas. You can read an entire csv into a df. The issue isn't their method, it's the implementation.

0

u/sinterkaastosti23 Jul 26 '24

damn for some reason i thought they were using polars lol.

And wdym by "you can read an entire csv into a df"? because polars can do that too

0

u/[deleted] Jul 25 '24

[deleted]