我有一个数据框。
category value percentage_difference
Cosmetics 789.99 300.0
Fruits 27.68 400.0
Clothes 179.20 500.0
我想添加第四列,使其值为类别(值,百分比)
category value percentage_difference merge_value
Cosmetics 789.99 300.0 Cosmetic(789.99, 300%)
Fruits 27.68 400.0 Fruits(27.68, 400%)
Clothes 179.20 500.0 Clothes(179.20, 500%
我可以使用for循环,没有for循环还有其他有效的方法吗?
答案 0 :(得分:4)
使用列表理解的另一种方法:
df['merge_value'] = ['{}({}, {:0}%)'.format(x, y, int(z)) for x, y, z in
df[['category', 'value', 'percentage_difference']].values]
[出]
category value percentage_difference merge_value
0 Cosmetics 789.99 300.0 Cosmetics(789.99, 300%)
1 Fruits 27.68 400.0 Fruits(27.68, 400%)
2 Clothes 179.20 500.0 Clothes(179.2, 500%)
答案 1 :(得分:4)
另一种方法是将列添加为字符串:
df=df.assign(merge_value=
df.category+"("+df.value.astype(str)+','+df.percentage_difference.astype(str)+"%)")
print(df)
category value percentage_difference merge_value
0 Cosmetics 789.99 300 Cosmetics(789.99,300%)
1 Fruits 27.68 400 Fruits(27.68,400%)
2 Clothes 179.20 500 Clothes(179.2,500%)
答案 2 :(得分:3)
Iterable
^
|
Collection
^
|
Set
^
|
SortedSet
^
|
NavigableSet
^
|
TreeSet