我试图对panda数据帧中的特定列求和。我从数据框中的文本开始,给定特定的单词,我将文本改为一个数字,然后求和。你知道吗
我首先创建一个示例数据帧:
import pandas as pd
df = pd.DataFrame({'a': [1,'produces','produces','understands','produces'], 'b' : [2,'','produces','understands','understands'], 'c' : [3,'','','understands','']})
transposed_df = df.transpose()
transposed_df
输出:
0 1 2 3 4
a 1 produces produces understands produces
b 2 produces understands understands
c 3 understands
这一切都很好,也正是我所期待的。然后,我将相关文本更改为整数,并创建一个(大部分)整数的数据帧。你知道吗
measure1 = transposed_df.iloc[:,[0,1,2]].replace('produces',1)
measure2 = transposed_df.iloc[:,[0,3]].replace('understands',1)
measure3 = transposed_df.iloc[:,[0,4]].replace('produces',1)
measures = [measure1, measure2, measure3]
from functools import reduce
counter = reduce (lambda left, right: pd.merge(left,right), measures)
counter
输出:
0 1 2 3 4
0 1 1 1 1 1
1 2 1 1 understands
2 3 1
这就是我所期望的。你知道吗
然后,我尝试对每行的第1列和第2列求和,并将其添加回转置的\u df中
transposed_df['first']=counter.iloc[:,[1,2]].sum(axis=1)
transposed_df
输出:
0 1 2 3 4 first
a 1 produces produces understands produces NaN
b 2 produces understands understands NaN
c 3 understands NaN
我希望最后一列是2,1,0。我做错什么了?你知道吗
有两个问题:求和和和插入不同索引的列。你知道吗
1) 总和
您的
df
属于objects
类型(所有字符串,包括空字符串)。数据帧counter
也是混合类型(int和string):请记住:
因此,尽管
counters
的第一行包含两个整数,但它们属于object
类型的系列(列),pandas不喜欢对它们进行汇总(显然您使用的是低于0.22.0的pandas版本,在以后的版本中,结果是0.0,默认值为min_count=0
,请参见sum)。你可以看到这个因此,解决方案是尽可能将对象显式地转换为数字(即整行由整数组成,而不是空字符串和整数):
结果:
2) 列插入
有不同的索引:
所以你用你的方法得到所有的南。最简单的方法是只插入序列的值,而不是序列本身(熊猫对齐索引:
结果:
相关问题 更多 >
编程相关推荐