如果我有一个具有以下列的数据框架:

1. NAME                                     object
2. On_Time                                      object
3. On_Budget                                    object
4. %actual_hr                                  float64
5. Baseline Start Date                  datetime64[ns]
6. Forecast Start Date                  datetime64[ns] 

我想能够说:对于这个数据框架,给我一个列的类型'对象'或类型'datetime'的列表?

我有一个函数,将数字('float64')转换为两个小数点后的位置,我想使用这个特定类型的数据帧列的列表,并通过这个函数将它们全部转换为2dp。

也许是这样的:

For c in col_list: if c.dtype = "Something"
list[]
List.append(c)?

当前回答

你可以在dtypes属性上使用布尔掩码:

In [11]: df = pd.DataFrame([[1, 2.3456, 'c']])

In [12]: df.dtypes
Out[12]: 
0      int64
1    float64
2     object
dtype: object

In [13]: msk = df.dtypes == np.float64  # or object, etc.

In [14]: msk
Out[14]: 
0    False
1     True
2    False
dtype: bool

您可以只查看那些具有所需dtype的列:

In [15]: df.loc[:, msk]
Out[15]: 
        1
0  2.3456

现在你可以使用round(或其他)并将其赋值回去:

In [16]: np.round(df.loc[:, msk], 2)
Out[16]: 
      1
0  2.35

In [17]: df.loc[:, msk] = np.round(df.loc[:, msk], 2)

In [18]: df
Out[18]: 
   0     1  2
0  1  2.35  c

其他回答

你可以在dtypes属性上使用布尔掩码:

In [11]: df = pd.DataFrame([[1, 2.3456, 'c']])

In [12]: df.dtypes
Out[12]: 
0      int64
1    float64
2     object
dtype: object

In [13]: msk = df.dtypes == np.float64  # or object, etc.

In [14]: msk
Out[14]: 
0    False
1     True
2    False
dtype: bool

您可以只查看那些具有所需dtype的列:

In [15]: df.loc[:, msk]
Out[15]: 
        1
0  2.3456

现在你可以使用round(或其他)并将其赋值回去:

In [16]: np.round(df.loc[:, msk], 2)
Out[16]: 
      1
0  2.35

In [17]: df.loc[:, msk] = np.round(df.loc[:, msk], 2)

In [18]: df
Out[18]: 
   0     1  2
0  1  2.35  c

从pandas v0.14.1开始,可以使用select_dtypes()按dtype选择列

In [2]: df = pd.DataFrame({'NAME': list('abcdef'),
    'On_Time': [True, False] * 3,
    'On_Budget': [False, True] * 3})

In [3]: df.select_dtypes(include=['bool'])
Out[3]:
  On_Budget On_Time
0     False    True
1      True   False
2     False    True
3      True   False
4     False    True
5      True   False

In [4]: mylist = list(df.select_dtypes(include=['bool']).columns)

In [5]: mylist
Out[5]: ['On_Budget', 'On_Time']

我想出了这个三句话。

本质上,它是这样做的:

获取列名及其各自的数据类型。 我可以选择将它输出到csv。


inp = pd.read_csv('filename.csv') # read input. Add read_csv arguments as needed
columns = pd.DataFrame({'column_names': inp.columns, 'datatypes': inp.dtypes})
columns.to_csv(inp+'columns_list.csv', encoding='utf-8') # encoding is optional

这使得我在尝试动态生成模式时更加容易。希望这能有所帮助

如果你想要一个只有对象列的列表,你可以这样做:

non_numerics = [x for x in df.columns \
                if not (df[x].dtype == np.float64 \
                        or df[x].dtype == np.int64)]

然后如果你想要得到另一个数字列表

numerics = [x for x in df.columns if x not in non_numerics]

yoshiserry;

def col_types(x,pd):
    dtypes=x.dtypes
    dtypes_col=dtypes.index
    dtypes_type=dtypes.value
    column_types=dict(zip(dtypes_col,dtypes_type))
    return column_types