Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何使用两个for循环将列表变量复制到数据帧中的位置变量中?_Python 3.x_Pandas_Dataframe - Fatal编程技术网

Python 3.x 如何使用两个for循环将列表变量复制到数据帧中的位置变量中?

Python 3.x 如何使用两个for循环将列表变量复制到数据帧中的位置变量中?,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,我有一个dataframe,它有两列,分别称为locStuff和data。有人好心地告诉我如何在df中索引位置范围,以便它正确地将数据更改为附加到locStuff的单个整数,而不是dataframe索引,这很好,现在我看不到如何使用值列表更改该位置范围的数据值 import pandas as pd INDEX = list(range(1, 11)) LOCATIONS = [3, 10, 6, 2, 9, 1, 7, 5, 8, 4] DATA = [94, 43, 85, 10, 81

我有一个dataframe,它有两列,分别称为locStuff和data。有人好心地告诉我如何在df中索引位置范围,以便它正确地将数据更改为附加到locStuff的单个整数,而不是dataframe索引,这很好,现在我看不到如何使用值列表更改该位置范围的数据值

import pandas as pd


INDEX = list(range(1, 11))
LOCATIONS = [3, 10, 6, 2, 9, 1, 7, 5, 8, 4]
DATA = [94, 43, 85, 10, 81, 57, 88, 11, 35, 86]
# Make dataframe
DF = pd.DataFrame(LOCATIONS, columns=['locStuff'], index=INDEX)
DF['data'] = pd.Series(DATA, index=INDEX)

# Location and new value inputs
LOC_TO_CHANGE = 8
NEW_LOC_VALUE = 999
NEW_LOC_VALUE = [999,666,333]


LOC_RANGE = list(range(3, 6))

DF.iloc[3:6, 1] = ('%03d' % NEW_LOC_VALUE)
print(DF)

#I TRIED BOTH OF THESE SEPARATELY
for i in NEW_LOC_VALUE:
    for j in LOC_RANGE:
        DF.iloc[j, 1] = ('%03d' % NEW_LOC_VALUE[i])


print (DF)

i=0
while i<len(NEW_LOC_VALUE):
    for j in LOC_RANGE:
        DF.iloc[j, 1] = ('%03d' % NEW_LOC_VALUE[i])
    i=+1

print(DF)
尝试将locStuff设置为索引、赋值和重置索引:

输出:

    locStuff    data
0   3           999
1   10          43
2   6           85
3   2           10
4   9           81
5   1           57
6   7           88
7   5           333
8   8           35
9   4           666

Hi-Quang,当我运行这个:Hi-Quang,我看到它工作了,但我不明白为什么,是不是当你设置locStuff作为索引并使用loc而不是iloc时,它只改变loc\u范围内的那些值?我现在不知道为什么我首先选择了bloc而不是loc。@Windy71在坚果壳中,是的。谢谢Quang,非常感谢!
    locStuff data
1          3   999
2         10   43
3          6   85
4          2   10
5          9   81
6          1   57
7          7   88
8          5   333
9          8   35
10         4   666
DF.set_index('locStuff', inplace=True)
DF.loc[LOC_RANGE, 'data'] = NEW_LOC_VALUE
DF.reset_index(inplace=True)
    locStuff    data
0   3           999
1   10          43
2   6           85
3   2           10
4   9           81
5   1           57
6   7           88
7   5           333
8   8           35
9   4           666