I am reading from a csv-file, and have the current values in my dataframe, where width and height is min and max value.
JavaScript
x
3
1
name width heigth
2
apple [10, 20] [15, 18]
3
And now i want to split and format the columns and print them:
JavaScript
1
5
1
pd.DataFrame(df['width'].str.split(',').tolist(), columns=['width-min', 'width-max'])
2
pd.DataFrame(df['height'].str.split(',').tolist(), columns=['height-min', 'height-max'])
3
4
print(tabulate(df, headers='keys', tablefmt='psql'))
5
My problem is that it stills print:
JavaScript
1
3
1
name width heigth
2
apple [10, 20] [15, 18]
3
Whereas I want it to print:
JavaScript
1
3
1
name min-width max-width min-height max-height
2
apple 10 20 15 18
3
What am I doing wrong?
Advertisement
Answer
This code can help you ,
JavaScript
1
15
15
1
a = {"name":['apple'],
2
'width': ['[10, 20]'],
3
'heigth': ['[15, 18]']}
4
5
import pandas as pd
6
df = pd.DataFrame(a)
7
8
df['min-width'], df['max-width'] = df['width'].apply(lambda x: x.strip('][').split(', ')[0]),
9
df['width'].apply(lambda x: x.strip('][').split(', ')[1])
10
11
df['min-height'], df['max-height'] = df['heigth'].apply(lambda x: x.strip('][').split(', ')[0]),
12
df['heigth'].apply(lambda x: x.strip('][').split(', ')[1])
13
14
df = df.drop(['width','heigth'],axis=1)
15
The df
will be,
JavaScript
1
3
1
name min-width max-width min-height max-height
2
0 apple 10 20 15 18
3
please let me know if that helps you !! Also, I am open to optimized suggestions!!