这是对先前提出的问题(由我提出 :))的后续问题 Oneliner to create string column from multiple columns
我想将数据框中的子集列合并到一个新的字符串列中。 @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
