gpt4 book ai didi

python - Pandas 修剪数据的更好方法

转载 作者:搜寻专家 更新时间:2023-10-30 19:47:46 25 4
gpt4 key购买 nike

我目前有一个看起来像这样的数据框:

df = pd.DataFrame({'AAA' : [4,5,6,7], 'BBB' : [100,100,30,40],'CCC' : [100,100,30,-50]})

我还有数据框:

df1 = pd.DataFrame({'AAA' : [4], 'BBB' : [100]})

我在哪里定义

relevantColumns=['AAA','BBB']

这只是 df1 的列的列表。

我想找到 df1 出现在 df 中的索引。我目前有一些看起来像这样的东西,

trueNFalses=(df==df1)[columnsToSort] #This generates a boolean dataframe

#Now I want to find the row with two trues in it, this is the row where df1 appears.

numTrues=trueNFalses.sum(axis=1)

#Now I look through numTrues and find the index of every values of 2,
#because that is where there were two trues.

indices=numTrues[numTrues==len(columnsToSort)].axes

所以我做了一个关于计算的非常全面的事情,只是为了获得 df 具有 df1 具有的列的索引。我觉得做这一切很傻,因为我几乎可以肯定,在 Pandas 中一定有更好的方法来做到这一点。我的技术也有一些缺点,我很想解决但不知道如何解决。例如,我确实需要将索引作为数据框,但在我的代码中,它是一个 dtype 对象列表,这对于将来的处理来说很尴尬。

最佳答案

我想你可以试试mergereset_index然后索引值在 index 列中:

df = pd.DataFrame({'AAA' : [4,5,6,7], 
'BBB' : [100,100,30,40],
'CCC' : [100,100,30,-50]}, index=[2,3,4,5])

df1 = pd.DataFrame({'AAA' : [4], 'BBB' : [100]}, index=[8])

relevantColumns=['AAA','BBB']

print df
AAA BBB CCC
2 4 100 100
3 5 100 100
4 6 30 30
5 7 40 -50

print df1
AAA BBB
8 4 100

print pd.merge(df.reset_index(), df1, on=relevantColumns, how='right')
index AAA BBB CCC
0 2 4 100 100

print pd.merge(df.reset_index(), df1, on=relevantColumns, how='right')['index']
0 2
Name: index, dtype: int64

关于python - Pandas 修剪数据的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36754436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com