numpy 使用Python连接2个单独的Excel,基于1个条件

3okqufwl  于 9个月前  发布在  Python
关注(0)|答案(1)|浏览(76)

我有这两个相框
DF1
| 出生日期|仪式编号|
| --|--|
| 一八九五年九月三十日|月1|
| 一八八四年七月二十三日|月1|
| 一八八九年三月二十九日|第2|
| 一八六八年十月四日|第3|
| 一八九二年八月四日|第2|
DF2
| 指数|日期|
| --|--|
| 1 |1929-05-16|
| 2 |1930-04-03|
| 3 |1930-11-05|
我的想法是根据df 1处的ceremony_number列将两者合并。我的意思是,如果df 1“ceremony_number”]与df 2“index”]匹配,则获取df 2“dates”]并将其添加到新列df 1“date_oscar”]。新列应如下所示
DF1
| 出生日期|日期_奥斯卡|
| --|--|
| 1895年9月30日|1929-05-16|
| 1884年7月23日|1929-05-16|
| 1889年3月29日|1930-04-03|
| 1868-04-10| 1930-11-05|
| 1892-8-4| 1930-04-03|
我一直在努力,但是没有用

award_year = []
for index, row in df.iterrows():
    award_year.append(df1[(row['ceremony_number'] == df2['index'])])
df1['date_oscar'] = award_year

字符串
这就是错误:

Empty DataFrame Columns: [index, fechas] Index...


有什么建议吗?提前感谢!

mzsu5hc0

mzsu5hc01#

您可以在提取数字到df2indexmapceremony_number

df1['birthdate'] = pd.to_datetime(df1['birthdate'], format='%m/%d/%Y')
df2['dates'] = pd.to_datetime(df2['dates'], format='%Y-%m-%d')

num = df1['ceremony_number'].str.extract('^(\d+)', expand=False).astype(int)
df1['date_oscar'] = num.map(df2['dates'])

字符串
输出量:

>>> df1
   birthdate ceremony_number date_oscar
0 1895-09-30             1st 1929-05-16
1 1884-07-23             1st 1929-05-16
2 1889-03-29             2nd 1930-04-03
3 1868-04-10             3rd 1930-11-05
4 1892-04-08             2nd 1930-04-03


最小工作示例

data1 = {'birthdate': {0: '9/30/1895', 1: '7/23/1884', 2: '3/29/1889',
                       3: '4/10/1868', 4: '4/8/1892'},
         'ceremony_number': {0: '1st', 1: '1st', 2: '2nd', 3: '3rd', 4: '2nd'}}
df1 = pd.DataFrame(data1)

data2 = {'dates': {1: '1929-05-16', 2: '1930-04-03', 3: '1930-11-05'}}
df2 = pd.DataFrame(data2)

# df1
   birthdate ceremony_number
0  9/30/1895             1st
1  7/23/1884             1st
2  3/29/1889             2nd
3  4/10/1868             3rd
4   4/8/1892             2nd

# df2
        dates
1  1929-05-16
2  1930-04-03
3  1930-11-05

相关问题