Hoap Humanoid Hoap Humanoid - 1 year ago 75
Python Question

Read file into dataframe spliting the text after the first word in python

I have a file of strings

, where the first word is a class name and the rest is a description, like the following:

n01440764 tench, Tinca tinca
n01443537 goldfish, Carassius auratus
n01484850 great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias

I would like to read the file into a dataframe of two columns
with the class and
with the rest of the content.

Answer Source

You could do:

df = pd.read_csv(data, sep='\s{2,}', engine='python', names=['col'])

df['class'] = df['col'].str.split().apply(lambda x: x[0])
# Splitting on first occurence of whitespace
df['description'] = df['col'].str.join('').apply(lambda x: x.split(' ',1)[1])

print (df)

       class                                        description
0  n01440764                                 tench, Tinca tinca
1  n01443537                        goldfish, Carassius auratus
2  n01484850  great white shark, white shark, man-eater, man...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download