\n","author":{"@type":"Person","name":"Dmitry"},"upvoteCount":0,"answerCount":2,"acceptedAnswer":{"@type":"Answer","text":"
\ndf['grayscale255'] = df['grayscale255'].apply(lambda x: x.astype('uint8'))\n
\nOr apply
np.ubyte
:
df['grayscale255'] = df['grayscale255'].apply(np.ubyte)\n
\ndf
:
random_len grayscale255\n0 4 [72, 195, 17, 79]\n1 3 [70, 97, 198]\n2 4 [161, 129, 163, 48]\n3 2 [152, 22]\n4 3 [40, 23, 175]\n
\nSample Data:
\nimport numpy as np\nimport pandas as pd\n\nnp.random.seed(5)\n\ndf = pd.DataFrame({'random_len': np.random.randint(1, 5, size=5)})\ndf['grayscale255'] = df['random_len'].apply(\n lambda x: np.random.random(size=x) * 200\n)\n
\n random_len grayscale255\n0 4 [72.74737942011788, 195.8889998322892, 17.9642...\n1 3 [70.82760858300028, 97.32759937167242, 198.164...\n2 4 [161.6563366066534, 129.89177664881987, 163.89...\n3 2 [152.87452173223647, 22.180152347812744]\n4 3 [40.830949566118434, 23.81907149565208, 175.58...\n
\n","author":{"@type":"Person","name":"Henry Ecker"},"upvoteCount":2}}}Reputation: 737
I have a pandas dataframe. One of it's columns contains variable-length float arrays. I need to convert them to arrays of uint8 because actually these arrays contain grayscale images with values from 0 to 255. Currently arrays dimention is 1. I understand that it's possible to iterate over rows and do conversion in this cycle. But hope there is an out of box solution cause this task seems to be common. I also tryed the following df['grayscale255'] = df['grayscale255'].astype('uint8')
, but it doesn't work becuase
TypeError: only size-1 arrays can be converted to Python scalars
Upvotes: 0
Views: 2026
Reputation: 35686
df['grayscale255'] = df['grayscale255'].apply(lambda x: x.astype('uint8'))
Or apply
np.ubyte
:
df['grayscale255'] = df['grayscale255'].apply(np.ubyte)
df
:
random_len grayscale255
0 4 [72, 195, 17, 79]
1 3 [70, 97, 198]
2 4 [161, 129, 163, 48]
3 2 [152, 22]
4 3 [40, 23, 175]
Sample Data:
import numpy as np
import pandas as pd
np.random.seed(5)
df = pd.DataFrame({'random_len': np.random.randint(1, 5, size=5)})
df['grayscale255'] = df['random_len'].apply(
lambda x: np.random.random(size=x) * 200
)
random_len grayscale255
0 4 [72.74737942011788, 195.8889998322892, 17.9642...
1 3 [70.82760858300028, 97.32759937167242, 198.164...
2 4 [161.6563366066534, 129.89177664881987, 163.89...
3 2 [152.87452173223647, 22.180152347812744]
4 3 [40.830949566118434, 23.81907149565208, 175.58...
Upvotes: 2
Reputation: 85
df['grayscale255'] = df['grayscale255'].apply('uint8')
Try this
Upvotes: -1