说我有以下数据帧:
更新列feat和another_feat的值的最有效方法是什么,其中流是2号?
是这个吗?
for index, row in df.iterrows():
if df1.loc[index,'stream'] == 2:
# do something
Run Code Online (Sandbox Code Playgroud)
更新: 如果我有超过100列怎么办?我不想明确命名我想要更新的列.我想将每列的值除以2(流列除外).
所以要清楚我的目标是什么:
将所有值除以具有流2的所有行中的2,但不更改流列
我有一个数据帧 df
df = pd.DataFrame(np.arange(20).reshape(10, -1),
[['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd'],
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']],
['X', 'Y'])
Run Code Online (Sandbox Code Playgroud)
如何获取按索引第一级分组的第一行和最后一行?
我试过了
df.groupby(level=0).agg(['first', 'last']).stack()
Run Code Online (Sandbox Code Playgroud)
得到了
X Y
a first 0 1
last 6 7
b first 8 9
last 12 13
c first 14 15
last 16 17
d first 18 19
last 18 19
Run Code Online (Sandbox Code Playgroud)
这非常接近我想要的.如何保留1级索引并改为:
X Y
a a 0 1
d 6 7
b e 8 9
g 12 13 …Run Code Online (Sandbox Code Playgroud) 鉴于对pandas 0.20.0的更新和弃用.ix,我想知道使用剩余的.loc和最好的方法来获得相同的结果是什么.iloc.我刚回答了这个问题,但第二个选项(不使用.ix)似乎效率低下且冗长.
片段:
print df.iloc[df.loc[df['cap'].astype(float) > 35].index, :-1]
Run Code Online (Sandbox Code Playgroud)
这是使用条件和索引位置过滤时的正确方法吗?