Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the dtype of the contents of a column in python pandas?

This question is related to how to check the dtype of a column in python pandas.

An empty pandas dataframe is created. Following this, it's filled with data. How can I then check if any of its columns contain complex types?

index = [np.array(['foo', 'qux'])]
columns = ["A",  "B"]
df = pd.DataFrame(index=index, columns=columns)
df.loc['foo']["A"] = 1 + 1j
df.loc['foo']["B"] = 1
df.loc['qux']["A"] = 2
df.loc['qux']["B"] = 2

print df
for type in df.dtypes:
    if type == complex:
        print type

At the moment, I get the type as object which isn't useful.

          A  B
foo  (1+1j)  1
qux       2  2
like image 492
bluprince13 Avatar asked Sep 14 '25 14:09

bluprince13


1 Answers

Consider the series s

s = pd.Series([1, 3.4, 2 + 1j], dtype=np.object)
s

0         1
1       3.4
2    (2+1j)
dtype: object

If I use pd.to_numeric, it will upcast the dtype to complex if any are complex

pd.to_numeric(s).dtype

dtype('complex128')
like image 83
piRSquared Avatar answered Sep 16 '25 07:09

piRSquared