将类别列转换为 Python 中的一个字符串列
Casting columns of categories to one string column in Python
这是对之前提出的问题(由我提出 :))的跟进
我想将数据框中的子集列合并到一个新的字符串列中。 @Zero 很友好地给我解决了这个问题
import pandas as pd
df = pd.DataFrame({'gender' : ['m', 'f', 'f'],\
'code' : ['K2000', 'K2000', 'K2001']})
col_names = df.columns
df_str = df[col_names].astype(str).apply('_'.join, axis=1)
df_str
Out[17]:
0 K2000_m
1 K2000_f
2 K2001_f
dtype: object
但是,如果我引入间隔数据,这会失败
df = pd.DataFrame({'gender' : ['m', 'f', 'f'],\
'code' : ['K2000', 'K2000', 'K2001'],\
'num' : pd.cut([3, 6, 9], [0, 5, 10])})
col_names = df.columns
df_str = df[col_names].astype(str).apply('_'.join, axis=1)
理想情况下,我还想将数据转换为分类数据(同样失败)
df_cat = pd.concat([df['gender'].astype('category'), \
df['code'].astype('category'), \
df['num'].astype('category')], axis=1)
df_cat_str = df_cat[col_names].astype(str).apply('_'.join, axis=1)
这是怎么回事?我怎样才能达到所需的输出
0 K2000_m_(0, 5]
1 K2000_f_(5, 10]
2 K2001_f_(5, 10]
与上一个问题一样,col_names
应该是包含列的任何子集的列表(不一定是本例中的所有列)
您需要在 lambda 函数中将每一列分别转换为 str
:
df_str = df[col_names].apply(lambda x: '_'.join(x.astype(str)), axis=1)
print (df_str)
0 K2000_m_(0, 5]
1 K2000_f_(5, 10]
2 K2001_f_(5, 10]
dtype: object
这是对之前提出的问题(由我提出 :))的跟进
我想将数据框中的子集列合并到一个新的字符串列中。 @Zero 很友好地给我解决了这个问题
import pandas as pd
df = pd.DataFrame({'gender' : ['m', 'f', 'f'],\
'code' : ['K2000', 'K2000', 'K2001']})
col_names = df.columns
df_str = df[col_names].astype(str).apply('_'.join, axis=1)
df_str
Out[17]:
0 K2000_m
1 K2000_f
2 K2001_f
dtype: object
但是,如果我引入间隔数据,这会失败
df = pd.DataFrame({'gender' : ['m', 'f', 'f'],\
'code' : ['K2000', 'K2000', 'K2001'],\
'num' : pd.cut([3, 6, 9], [0, 5, 10])})
col_names = df.columns
df_str = df[col_names].astype(str).apply('_'.join, axis=1)
理想情况下,我还想将数据转换为分类数据(同样失败)
df_cat = pd.concat([df['gender'].astype('category'), \
df['code'].astype('category'), \
df['num'].astype('category')], axis=1)
df_cat_str = df_cat[col_names].astype(str).apply('_'.join, axis=1)
这是怎么回事?我怎样才能达到所需的输出
0 K2000_m_(0, 5]
1 K2000_f_(5, 10]
2 K2001_f_(5, 10]
与上一个问题一样,col_names
应该是包含列的任何子集的列表(不一定是本例中的所有列)
您需要在 lambda 函数中将每一列分别转换为 str
:
df_str = df[col_names].apply(lambda x: '_'.join(x.astype(str)), axis=1)
print (df_str)
0 K2000_m_(0, 5]
1 K2000_f_(5, 10]
2 K2001_f_(5, 10]
dtype: object