我无法找到一种方法来在pandas中对两个Series对象进行有效的元素最小化.例如,我可以轻松添加两个系列:
In [1]:
import pandas as pd
s1 = pd.Series(data=[1,1,1], index=[1,2,3])
s2 = pd.Series(data=[1,2,2,1], index=[1,2,3,4])
s1.add(s2)
Out[1]:
1 2
2 3
3 3
4 NaN
dtype: float64
Run Code Online (Sandbox Code Playgroud)
但我找不到一种有效的方法来在两个系列之间进行元素最小化(同时对齐索引和处理NaN值).
没关系.有一个带有combine功能的逃生舱,所以你可以放入任何元素功能:
In [2]:
s1 = pd.Series(data=[1,1,1], index=[1,2,3])
s2 = pd.Series(data=[1,2,2,1], index=[1,2,3,4])
s1.combine(s2, min, 0)
Out[2]:
1 1
2 1
3 1
4 0
dtype: int64
Run Code Online (Sandbox Code Playgroud) 当groupby计数多个列时,我得到一个错误.这是我的数据框,也是一个简单标记不同的'b'和'c'组的示例.
df = pd.DataFrame(np.random.randint(0,2,(4,4)),
columns=['a', 'b', 'c', 'd'])
df['gr'] = df.groupby(['b', 'c']).grouper.group_info[0]
print df
a b c d gr
0 0 1 0 0 1
1 1 1 1 0 2
2 0 0 1 0 0
3 1 1 1 1 2
Run Code Online (Sandbox Code Playgroud)
但是,当稍微更改示例以便调用count()而不是grouper.group_info [0]时,会出现错误.
df = pd.DataFrame(np.random.randint(0,2,(4,4)),
columns=['a', 'b', 'c', 'd'])
df['gr'] = df.groupby(['b', 'c']).count()
print df
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-70-a46f632214e1> in <module>()
1 df = pd.DataFrame(np.random.randint(0,2,(4,4)),
2 columns=['a', 'b', 'c', 'd'])
----> 3 df['gr'] …Run Code Online (Sandbox Code Playgroud)