pandas:访问其他df中i索引值对应的i列值

2024-05-29 03:05:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图访问一个数据帧中的列值,比如说new_df对应于另一个df(比如df1)中的索引I

新的_df看起来是这样的:

Id          100120  100142  118365  269946  621382
2018-12-31       0       0       0       0       0
2019-01-31       0      40       0       0       0
2019-02-28      16      48       0       0       0

和df1:

0  100121        high  not_seasonal      trending
1  100140        high  not_seasonal      trending
2  118360        high      seasonal  not_trending

我知道这很容易做到,如下所示:

for i in df1.index:
    new_df.iloc[:,i].values

它返回new_df的i列中包含的所有列的类似数组的输出 第1列的示例

gogo [  0  40  48  ]

但是,问题在于在函数中访问新df的i列,其中i作为参数传递 例如:

def timeseriesCVscore(i):
    errors = []
    values = df1.loc[new_df.iloc[:,i]].values 
    .....

def timeseriesCVscore(i):
   
    errors = []
    
    for i in seasonal_profile_df.index:
        values = new_df.iloc[:,i].values

两者都会产生相同的错误:

KeyError: "Passing list-likes to .loc or [] with any missing labels is no longer supported. The following labels were missing: Int64Index([40, 48], dtype='int64')

我的代码结构如下,以便在新的_df中自动迭代i

for in df1:
    return timeseriesCVscore(i)

并获取包含i列的所有值的数组的输出

我找不到在基金会内部工作的方法,任何帮助都将不胜感激

更新:在函数内部进行试用

    for f in seasonal_profile_df.index:
        values = np.where((seasonal_profile_df.index[f] == i), new_df.loc[:,i].values, 0)

给出以下错误:

KeyError: "None of [Int64Index([0, 0, 16], dtype='int64', name='Id')] are in the [columns]"


Tags: indfnewforindexnotprofileloc
1条回答
网友
1楼 · 发布于 2024-05-29 03:05:00

关于您的代码:

def timeseriesCVscore(i):
    errors = []
    values = df1.loc[new_df.iloc[:,i]].values 

在i=1的情况下,“new_df.iloc[:,1]”的结果为:

Id
2018-12-31     0
2019-01-31    40
2019-02-28    48
Name: 100142, dtype: int64

因此,0、40和48被用作df1的标签,就好像:

df1.loc([0,40,48])

但是,正如您在错误消息末尾所看到的,df1没有标签40或48

The following labels were missing: Int64Index([40, 48], dtype='int64')

相关问题 更多 >

    热门问题