如何连接 pandas 数据框列 [英] How to concat Pandas dataframe columns
本文介绍了如何连接 pandas 数据框列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Pandas数据帧中合并不同数据类型的列,这样,如果列number
与列operator
连接在一起,并且我执行了groupby('user').sum()
,则可以进行适当的聚合:
How to concat columns of different data types in a Pandas dataframe such that if column number
is concatenated with column operator
, and I do a groupby('user').sum()
, I can have the appropriate aggregation:
number operator user
id
1 193 - A
2 332 + B
3 4434 + A
4 432 - C
5 652 + C
6 567 + D
#after concat:
number operator user
id
1 -193 - A
2 332 + B
3 4434 + A
4 -432 - C
5 652 + C
6 567 + D
#df.groupby('user').sum()
number
user
A 4241
B 332
C 220
D 567
推荐答案
使用loc
和布尔掩码使'number'值为负:
Use loc
with boolean mask to make the 'number' values negative:
In [34]:
df.loc[df['operator'] == '-', 'number'] = -df['number']
df
Out[34]:
number operator user
id
1 -193 - A
2 332 + B
3 4434 + A
4 -432 - C
5 652 + C
6 567 + D
然后您可以在'用户'上的groupby
可以在'号码'列上调用sum
:
You can then groupby
on 'user' can call sum
on 'number' column:
In [35]:
df.groupby('user')['number'].sum()
Out[35]:
user
A 4241
B 332
C 220
D 567
Name: number, dtype: int64
这篇关于如何连接 pandas 数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文