-
明月笑刀无情
DataFrame 和 Pandas 将是做到这一点的最佳方式。但是,我试图找出这是否也可以使用基本循环来完成。这是我使用列表理解能够做的事情。我将把每一行用作一个字符串。然后我只需要比较每行中的前 4 个字符。我是这样做的。它只是两行代码。x = ['myID name day age','111 james Feb 29','112 alexs Mar 19','113 kevin Jan 18','114 bratt Jul 22','115 nancy Apr 30']y = ['myID visitedCity','111 boston','111 san fran','111 paris','112 texas','113 fargo','114 austin','114 los alto','115 memphis']k = [i.ljust(16,' ')+j[4:] for i in y for j in x if i[:3] == j[:3]]for x in k: print(x)输出如下:myID visitedCity name day age111 boston james Feb 29111 san fran james Feb 29111 paris james Feb 29112 texas alexs Mar 19113 fargo kevin Jan 18114 austin bratt Jul 22114 los alto bratt Jul 22115 memphis nancy Apr 30
-
慕哥9229398
使用merge命令。>>> import pandas as pandas>>> adf = pandas.DataFrame([[111, 'james', 'Feb', 29]])>>> adf.columns = ['myID', 'name', 'day', 'age']>>> adf myID name day age0 111 james Feb 29>>> bdf = pandas.DataFrame([[111, 'boston'], [111, 'san fran']])>>> bdf.columns = ['myID', 'visitiedCity']>>> bdf myID visitiedCity0 111 boston1 111 san fran>>> df = pandas.merge(bdf, adf, how='outer', on=['myID'], indicator=False)>>> df myID visitiedCity name day age0 111 boston james Feb 291 111 san fran james Feb 29可以找到更多信息https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html
-
一只萌萌小番薯
尝试import pandas as pdaDf= pd.read_csv('a.csv')bDf =pd.read_csv('b.csv')ResultDf=pd.merge( bDf, aDf, how='left', on='myID')