I read a text file in Python, and I wonder how to read it from a specific line

Asked 2 years ago, Updated 2 years ago, 114 views

For example, like this

Reports

Contents

Number Name Gender

1 Hong Gil-dong Nam

2 Kim Chul-soo Nam

3 Lee Young-hee female

When text is written like this, if you're trying to get only gender content, how do you do it? Should I make a code? They are separated by tabs

open txt python3.6

2022-09-21 12:15

1 Answers

This is how to use pandas read_csv. Specify tab delimiter with sep, specify rows to skip to skip to skip.

import pandas as pd
from io import StringIO


text = '' report
content
Number\tName\tGender
1\tHong Gil-dong\tNam
2\tKim Chul-soo\tNam
3\t Lee Younghee\t''

df = pd.read_csv(StringIO(text), sep='\t', skiprows=2)
df = df.set_index ('number')
print(df.head(100))
print('---------gender-------')
print(df['Gender'])

print('---------Name---------')
print(df['name'])
 Name Gender
Number
1 Hong Gil Dong Nam
2 Kim Chul-soo Nam
3. Lee Younghee
--------- Gender-------
Number
one son
second son
three women
Name: Gender, dtype: object
--------- Name-----------
Number
1 Hong Gil-dong
2 Kim Chul-soo
3 Lee Younghee
Name: name, dtype: object


2022-09-21 12:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.