Python 使用Pandas将一个字符串列组合到另一个字符串列
如果我有以下数据帧:Python 使用Pandas将一个字符串列组合到另一个字符串列,python,pandas,Python,Pandas,如果我有以下数据帧: id categories products 01 fruit Apple, Apricot 02 fruit Apple, Banana, Clementine, Pear 03 fruit Orange, Pineapple, Pear 04 vegetable Carrot, Cabbage 我想创建一个像这样的新df,我应该怎么做?谢谢 id
id categories products
01 fruit Apple, Apricot
02 fruit Apple, Banana, Clementine, Pear
03 fruit Orange, Pineapple, Pear
04 vegetable Carrot, Cabbage
我想创建一个像这样的新df,我应该怎么做?谢谢
id products
01 (fruit)Apple, Apricot
02 (fruit)Apple, Banana, Clementine, Pear
03 (fruit)Orange, Pineapple, Pear
04 (vegetable)Carrot, Cabbage
试试这个
df = df.set_index('id')
df =df.apply(lambda x: "(" + x['categories'] + ")" + x['products'],axis=1).to_frame('products')
print df
只对字符串求和
"(" + df.categories + ")" + df.products
在这一点上,为什么不仅仅是
”(“+x.categories+”)“+x.products
?为了维护“id”,您仍然可以这样做;直接方法似乎比使用apply
更简单、更有效。您知道为什么df['format']='({0}){1}。format(df.categories,df.products)
不能以这种方式工作吗?@aydow因为您将获得参数转换的结果(在本例中,系列
对象df.categories
和df.products
)到字符串
,并将其替换为`{0}`和{1}
。结果将是单个字符串,而不是您可能想要的系列