我从列表列表中创建了一个DataFrame:
table = [
['a', '1.2', '4.2' ],
['b', '70', '0.03'],
['x', '5', '0' ],
]
df = pd.DataFrame(table)
如何将列转换为特定类型?在本例中,我想将列2和列3转换为浮点数。
是否有一种方法可以在转换到DataFrame时指定类型?还是先创建DataFrame,然后循环遍历列以更改每列的类型更好?理想情况下,我希望以动态的方式进行此操作,因为可能有数百个列,而我不想确切地指定哪些列属于哪种类型。我所能保证的是每一列都包含相同类型的值。
用这个:
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df
Out[16]:
one two three
0 a 1.2 4.2
1 b 70 0.03
2 x 5 0
df.dtypes
Out[17]:
one object
two object
three object
df[['two', 'three']] = df[['two', 'three']].astype(float)
df.dtypes
Out[19]:
one object
two float64
three float64
Df.info()给出了temp的初始数据类型,即float64
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 date 132 non-null object
1 temp 132 non-null float64
现在,使用这段代码将数据类型更改为int64:
df['temp'] = df['temp'].astype('int64')
如果你再次执行df.info(),你会看到:
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 date 132 non-null object
1 temp 132 non-null int64
这表明您已经成功更改了列temp的数据类型。编码愉快!
创建两个数据框架,每个数据框架的列都有不同的数据类型,然后将它们附加在一起:
d1 = pd.DataFrame(columns=[ 'float_column' ], dtype=float)
d1 = d1.append(pd.DataFrame(columns=[ 'string_column' ], dtype=str))
结果
In[8}: d1.dtypes
Out[8]:
float_column float64
string_column object
dtype: object
创建数据帧后,可以在第一列中使用浮点变量填充它,在第二列中使用字符串(或任何您想要的数据类型)填充它。
下面是一个函数,它以一个DataFrame和一个列列表作为参数,并将列中的所有数据强制转换为数字。
# df is the DataFrame, and column_list is a list of columns as strings (e.g ["col1","col2","col3"])
# dependencies: pandas
def coerce_df_columns_to_numeric(df, column_list):
df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')
举个例子:
import pandas as pd
def coerce_df_columns_to_numeric(df, column_list):
df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col1','col2','col3'])
coerce_df_columns_to_numeric(df, ['col2','col3'])