Naruto
Naruto

Reputation: 139

dataframe transformation of pandas dataframe

I want to manipulate the dataframe element into the data type of the element. the example below dataframe.

A      B         C           D
1      2       12-03-2010   1
45     acxz    3-02-2010    3
43     2.9     14-08-2010   4
45.3   3.5     23-09-2019   2.46
nan    34.23   09-09-2020   09-02-2015
45     nan     sam          10-09-2016
24     45.23   02-03-2021   wax
xyz    32      raz          na

Transform this dataframe into below dataframe.

A        B         C         D
int     int     datetime    int
int     string  datetime    int
int     float   datetime    int
float   float   datetime    float
string  float   datetime    datetime
int     string  string      datetime
int     float   datetime    string
string  int     string      string

can anyone suggest me any way to achieve the below dataframe from the above data using pandas.

Upvotes: 0

Views: 39

Answers (1)

jezrael
jezrael

Reputation: 862406

Use DataFrame.applymap by types, convert to strings and last use replace:

df = pd.DataFrame({
    "a": [1, 0.01, 'aaa', pd.to_datetime('2015-01-01')],
    "b": ['yy', pd.to_datetime('2015-01-01'), 1, 0]
   
})

d = {"<class 'pandas._libs.tslibs.timestamps.Timestamp'>":'datetime',
     "<class 'int'>":'int',
     "<class 'float'>":'float',
     "<class 'str'>":'string'}
df = df.applymap(type).astype(str).replace(d)
print (df)
          a         b
0       int    string
1     float  datetime
2    string       int
3  datetime       int

Upvotes: 1

Related Questions