首页 > 解决方案 > 如何使用两个 for 循环将列表变量复制到数据框中的位置变量中?

问题描述

我有一个数据框,它有 2 列称为 locStuff 和数据。有人很友好地向我展示了如何在 df 中索引位置范围,以便它正确地将数据更改为附加到 locStuff 而不是数据帧索引的单个整数,这工作正常,现在我看不到如何更改数据值该位置范围的值列表。

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)

这些都不起作用:

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

我知道如何对空列表使用循环或列表推导来做到这一点,但不知道如何将我上面的内容用于 DataFrame。

预期的行为将是:

    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

标签: python-3.xpandasdataframe

解决方案


尝试设置locStuff为索引,分配值,然后reset_index

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

推荐阅读