Python 使用具有列表理解的iloc设置值
我试图使用列表理解来迭代数据帧,并使用iloc为位置设置一个新值。我已经确认它正在正确地迭代Python 使用具有列表理解的iloc设置值,python,pandas,list-comprehension,Python,Pandas,List Comprehension,我试图使用列表理解来迭代数据帧,并使用iloc为位置设置一个新值。我已经确认它正在正确地迭代 import pandas as pd import numpy as np df = pd.DataFrame([np.arange(10)]*10) #working for i in range(10): for j in range(10): df.iloc[i,j] = 0+i #not working [df.iloc[i,j] = 5 for i in ra
import pandas as pd
import numpy as np
df = pd.DataFrame([np.arange(10)]*10)
#working
for i in range(10):
for j in range(10):
df.iloc[i,j] = 0+i
#not working
[df.iloc[i,j] = 5 for i in range(10) for j in range(10)]
有人能解释一下为什么上述方法不起作用吗?否则会怎么样?这不起作用,因为列表理解需要在最左边的位置使用Python表达式
[df.iloc[i,j] = 5 for i in range(10) for j in range(10)]
^^^^^^^^^^^^^^^^
# This is a statement, not an expression.
这是Python语言语法的结果,在这里正式指定:
我想,你可以重写它来使用高级索引。为清晰起见,对行和列使用不同的尺寸:
import pandas
import numpy
df = pandas.DataFrame([numpy.arange(4)]*7)
之后的df
为:
0 1 2 3
0 0 1 2 3
1 0 1 2 3
2 0 1 2 3
3 0 1 2 3
4 0 1 2 3
5 0 1 2 3
6 0 1 2 3
0 1 2 3
0 125 125 100 3
1 125 125 2 3
2 125 125 100 3
3 125 125 2 3
4 125 125 100 3
5 125 125 2 3
6 0 1 2 3
您可以使用“花式索引”进行分配,即在列表中提供索引:
df.iloc[[0, 2, 4], [2]] = 100
df.iloc[list(range(6)), list(range(2))] = 125
之后的df
为:
0 1 2 3
0 0 1 2 3
1 0 1 2 3
2 0 1 2 3
3 0 1 2 3
4 0 1 2 3
5 0 1 2 3
6 0 1 2 3
0 1 2 3
0 125 125 100 3
1 125 125 2 3
2 125 125 100 3
3 125 125 2 3
4 125 125 100 3
5 125 125 2 3
6 0 1 2 3
您在listcomp中执行赋值语句df.iloc[i,j]=5,所以它不起作用
df.iloc[i,j]=5
不会为listcomp返回任何要创建列表的内容,并且listcomp不允许使用语句。您需要listcomp之外的Assignment语句。您的listcomp可能会更改为此
df[:] = [[5 for j in range(10)] for i in range(10)]
Out[17]:
0 1 2 3 4 5 6 7 8 9
0 5 5 5 5 5 5 5 5 5 5
1 5 5 5 5 5 5 5 5 5 5
2 5 5 5 5 5 5 5 5 5 5
3 5 5 5 5 5 5 5 5 5 5
4 5 5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5 5 5
6 5 5 5 5 5 5 5 5 5 5
7 5 5 5 5 5 5 5 5 5 5
8 5 5 5 5 5 5 5 5 5 5
9 5 5 5 5 5 5 5 5 5 5
然而,我想这只是一个用来说明问题的例子,因为有更好的方法来创建这样的数据框架。列表理解用于构建列表。如果您没有构建列表,那么就不应该使用列表理解。