两只Pandas串的搭配

2024-04-26 01:16:54 发布

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

我在两个不同的dataframe中有两个(address)列,每个列的长度不同,我希望从一个dataframe的一个列到另一个dataframe的另一个列迭代每个元素。这意味着,我希望检查第一个dataframe第一列中的每个元素是否与第二个dataframe的第二列中的任何元素匹配并返回一个布尔值。在

如何在python中实现上述功能?在

数据帧1:

0 New Delhi, India
1 Mumbai, India
2 Bangalore, India
3 Dwarka, New Delhi, India

数据帧2:

^{pr2}$

结果:(长度应等于df 1第1列的长度)

True
False
False
True

Tags: 数据功能falsetrue元素dataframedfnew
1条回答
网友
1楼 · 发布于 2024-04-26 01:16:54
import pandas as pd
sales1 = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140},
     {'account': 'Alpha Co',  'Jan': 200, 'Feb': 210, 'Mar': 215},
     {'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 }]

sales2 = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140},
     {'account': 'A',  'Jan': 200, 'Feb': 210, 'Mar': 215},
     {'account': 'S',  'Jan': 50,  'Feb': 90,  'Mar': 95 }]

df1 = pd.DataFrame(sales1)
df2 = pd.DataFrame(sales2)

def CheckDF(df1,df2):
    for (item, Value),(item1, Value1) in 
    zip(df1['account'].iteritems(),df2['account'].iteritems()):
        if len(str(Value).strip()) == len(str(Value1).strip()):
            print(True)
        else:
            print(False)

CheckDF(df1,df2)

DF1:

^{pr2}$

DF2:

   Feb  Jan  Mar    account
0  200  150  140  Jones LLC
1  210  200  215          A
2   90   50   95          S

输出:

True
False
False

相关问题 更多 >