Pandas save tuple as a value in a column

user4789408 :

I am working on a DataFrame and I need to save tuple as value in a specific column.

df['column'] = (423423,41231,5345)

After saving the DataFrame to a .csv if I want to get back the value I can't use the tuple again, because it has been saved as a string.

Is there any way to save a tuple (or also object in general) as a value?

It there any specific function in pandas or other library, which allows to transform the previous tuple (saved as string) as a tuple again?

anky_91 :

csv cannot store python objects , you should use pickle to_pickle and read_pickle instead.

Example:

df = pd.DataFrame({'A':[(1,2,3),(4,5,6),(7,8,9)],'B':list('xyz')})

print(df)
           A  B
0  (1, 2, 3)  x
1  (4, 5, 6)  y
2  (7, 8, 9)  z

df.to_pickle('test.pkl')
new_df = pd.read_pickle('test.pkl')
print(new_df)

           A  B
0  (1, 2, 3)  x
1  (4, 5, 6)  y
2  (7, 8, 9)  z

type(new_df.loc[0,'A'])
#tuple

For a csv , when you read a csv , the values are returned as a string to which you can apply ast.literal_eval like df['Col_name'].apply(ast.literal_eval) after importing ast

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33359&siteId=1