python - Pandas df,总和列列表,但不是全部
问题描述
使用下一个熊猫的 df 时,例如:
In [79]: df
Out[79]:
2 4 12
S [0, 4, 1] [1, 2, 0] [0, 4, 1]
R [0, 2, 1] [0, 2, 3] NaN
E [0, 1, 1] [1, 0, 1] NaN
A [1, 1, 2] [0, 1, 3] [0, 2, 4]
B [0, 1, 1] [0, 1, 0] [0, 0, 1]
D [3, 0, 2] [2, 1, 2] [1, 0, 2]
仅对于像“E”或“D”这样的索引需要考虑值之一是否为 gt 0,不会是总和的一部分,例如:
In [85]: df.loc['D']
Out[85]:
2 [3, 0, 2]
4 [2, 1, 2]
12 [1, 0, 2]
Name: D, dtype: object
In [88]: df.loc['E']
Out[88]:
2 [0, 1, 1]
4 [1, 0, 1]
12 NaN
Name: E, dtype: object
所有 df['D' 或 'E' index ][any keys][2] 都是 gt 0,因此不会成为总和的一部分。
我可以像这样一次性总结所有内容:
In [89]: df.fillna(0).applymap(np.array).sum()
Out[89]:
2 [4, 9, 8]
4 [4, 7, 9]
12 [1, 6, 8]
dtype: object
In [90]:
但我需要删除我提到的那些值,并期望得到类似的结果:
Out[x]:
2 [4, 9, 5]
4 [3, 7, 6]
12 [1, 6, 6]
如果我只能得到 2 列,那就更好了:
Out[x]:
neg pos
2 4 5
4 3 6
12 1 6
我不知道如何获得理想的结果,非常欢迎任何提示......
更新:找到了一个解决方案!转换为 Pandas 的系列,例如:
从数据框中得到:
In [65]: df[4]
Out[65]:
S [1, 2, 0]
R [0, 2, 3]
E [0, 0, 1]
A [0, 1, 3]
B [0, 1, 0]
D [2, 1, 2]
Name: 4, dtype: object
转换为系列:
In [66]: plaAction[4]
Out[66]:
0 1 2
S 1 2 0
R 0 2 3
E 0 0 1
A 0 1 3
B 0 1 0
D 2 1 2
最后我的代码是:
# define new empty dictionary
plaAction = {}
# Define Total using each column for new Panda's series
Tneg, Tcon, Tpos = (0, 1, 2)
# From dataframe to series
for pn, plaCol in enumerate(df.columns):
#Converting to series and separating list values for each key
plaAction[plaCol] = df_copy[plaCol].apply(pd.Series)
# Sum desired values, dropping the ones gt 0
Tpos = int(plaAction[plaCol][Tpos].drop(labels=['D', 'E']).sum())
Tneg = int(plaAction[plaCol][Tneg].sum())
print("Player: "+str(plaCol) +"\tTpos: "+str(Tpos) +"\tTneg: "+str(Tneg))
所需的输出:
Player: 2 Tpos: 5 Tneg: 4
Player: 4 Tpos: 6 Tneg: 3
Player: 12 Tpos: 6 Tneg: 1
解决方案
推荐阅读
- sql - INNER JOIN 的别名引用了字段列表 SQL 中的一列
- javascript - 在第一页加载时触发输入文件点击模式不会触发
- vue.js - Vue js如何在v-for循环中渲染大括号变量
- angular - 来自多个孩子的输出和发射器
- android - 我添加了隐私政策来玩商店和我的应用程序。我的应用程序已经 10 个小时没有再次发布
- asp.net-mvc - .Net Core MVC 2.1 中是否有等效的会话开始?
- sql - 使用“BEGIN TRANSACTION”和“END TRANSACTION”来提高性能
- javafx - 带有 JavaFx 11 和 JDK 11 的 Netbeans 9.0
- android - 如何在android的firebase数据库中仅获取最近添加的消息
- python - Python在不使用函数的情况下获取当前类名