如何从列表中提取项目并将其添加为数据框中的列?
How to extract an item from a list and add it as a column in dataframe?
我有 3 个列表,如下所示
numeric_cols = df.select_dtypes(include=np.number).columns # 3 items `qty`, `age`, `sqft`
date_cols = df.select_dtypes(include=['datetime64']).columns # 2 items
string_cols = df.select_dtypes(include=['object']).columns # 3 items `bucket`, `category`, `level`
现在,我想
a) select 数字列中只有一项 - qty
和 string_cols
中的所有项目(因此数据框必须只有 4 列)
我尝试了以下
df[[*string_cols]] = df[[*string_cols]]
df.insert(2, "Qty",df['Qty'],True)
请注意,我展示的只是一个示例。在实际数据中,我有数百万行和数百列。因此,我想遵循上述方法。
可以指导我如何有效地做到这一点吗?
您可以 select 使用列名列表的列子集:
new_df = df[[*string_cols] + ['Qty']]
例如,对于 DataFrame,
Qty Age Sqft bucket category level
0 11 8 1.0 a a a
1 2 9 0.0 b b b
2 3 10 0.0 c c c
3 18 3 1.0 d d d
4 21 2 NaN e e e
string_cols = df.select_dtypes(inclue=['object']).columns
new_df = df[[*string_cols] + ['Qty']]
产生:
bucket category level Qty
0 a a a 11
1 b b b 2
2 c c c 3
3 d d d 18
4 e e e 21
我有 3 个列表,如下所示
numeric_cols = df.select_dtypes(include=np.number).columns # 3 items `qty`, `age`, `sqft`
date_cols = df.select_dtypes(include=['datetime64']).columns # 2 items
string_cols = df.select_dtypes(include=['object']).columns # 3 items `bucket`, `category`, `level`
现在,我想
a) select 数字列中只有一项 - qty
和 string_cols
中的所有项目(因此数据框必须只有 4 列)
我尝试了以下
df[[*string_cols]] = df[[*string_cols]]
df.insert(2, "Qty",df['Qty'],True)
请注意,我展示的只是一个示例。在实际数据中,我有数百万行和数百列。因此,我想遵循上述方法。
可以指导我如何有效地做到这一点吗?
您可以 select 使用列名列表的列子集:
new_df = df[[*string_cols] + ['Qty']]
例如,对于 DataFrame,
Qty Age Sqft bucket category level
0 11 8 1.0 a a a
1 2 9 0.0 b b b
2 3 10 0.0 c c c
3 18 3 1.0 d d d
4 21 2 NaN e e e
string_cols = df.select_dtypes(inclue=['object']).columns
new_df = df[[*string_cols] + ['Qty']]
产生:
bucket category level Qty
0 a a a 11
1 b b b 2
2 c c c 3
3 d d d 18
4 e e e 21