我想要在熊猫数据框架中使用某一列的索引子集。然而,当我使用值列表作为我的子集时,我会收到一个错误,这似乎是其他用户面临的一个非常常见的错误。我尝试过在以前的帖子中提出不同的解决方案,但没有一个方案对我有帮助。
import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.DataFrame({'A': [5,6,3,4,5], 'B': [1,2,3,5,1]})
#I create a new column combining the first two columns
df["C"] = df['A'].astype(str) +"-"+ df["B"].astype(str)
#Then, I randomly select two values from the unique values coming from column C
uniqueVal = pd.unique(df["C"])
my_subset = uniqueVal[np.random.choice(len(uniqueVal), size=2, replace=False)]
#Let's print my_subset
print(my_subset)
array(['3-3', '4-5'], dtype=object)
#Now, I would like to get all the rows containing my_subset values in column C
df[df['C']].isin(my_subset)
在这里,我得到的错误如下:
"None of [Index(['5-1', '6-2', '3-3', '4-5', '5-1'], dtype='object')] are in the [columns]"
发布于 2022-07-14 18:16:49
当您检查df的C/ col是否在您的列表中时,分组操作不当
它应该是dfcondition格式的。
#change the last line
print(df[df['C'].isin(my_subset)])
输出
A B C
2 3 3 3-3
3 4 5 4-5
https://stackoverflow.com/questions/72984990
复制相似问题