这是我最初的df
China USA
2009 NaN -9
2010 1.2 8
2011 1.5 NaN
2014 5.0 NaN
2015 NaN 8
然后我使用reindex方法添加一些索引
frame2=frame1.reindex([2009,2010,2011,2012,2013,2014,2015,2016],method="ffill")
我希望第2帧通过
China USA
2009 NaN -9
2010 1.2 8
2011 1.5 NaN
2012 NaN NaN
2013 NaN NaN
2014 5.0 NaN
2015 NaN 8
2016 NaN NaN
到
China USA
2009 NaN -9
2010 1.2 8
2011 1.5 8
2012 1.5 8
2013 1.5 8
2014 5.0 8
2015 5.0 8
2016 5.0 8
但它返回了
China USA
2009 NaN -9
2010 1.2 8
2011 1.5 NaN
2012 1.5 NaN
2013 1.5 NaN
2014 5.0 NaN
2015 NaN 8
2016 NaN 8
它仅填充了我df的某些条目。
答案 0 :(得分:3)
从某种意义上说,它确实进行了前期填充。它从import numpy as np
import re
waters = np.full((10,10), '##','U2')
headers = ['A','B','C','D','E','F','G','H','I','J']
#PRINTS THE BOARD
def printBoard():
for i,header in enumerate(headers):
if i == 0:
print(' ',end='')
print(header + ' ',end='')
if i == len(headers)-1: print()
for x,line in enumerate(waters):
print('%2d'%(x),end='')
[print(' '+pos,end='') for pos in line]
print()
printBoard()
board_x_coord = {
"A":0,
"B":1,
"C":2,
"D":3,
"E":4,
"F":5,
"G":6,
"H":7,
"I":8,
"J":9
}
ship_type = [
["CV","Carrier",5],
["BB","Battleship",4],
["CA","Cruiser",3],
["SS","Submarine",3],
["DD","Destroyer",2],
]
def board_coord_to_npcoord(ship,coord):
try:
result = re.findall(r'([A-J])(\d)([A-J])(\d)',coord)[0]
x_crd_a = board_x_coord.get(result[0])
y_crd_a = int(result[1])
x_crd_b = board_x_coord.get(result[2])
y_crd_b = int(result[3])
vertical = ship[2] == abs(x_crd_b - x_crd_a + 1) and y_crd_a == y_crd_b
horizontal = ship[2] == abs(y_crd_b - y_crd_a + 1) and x_crd_a == x_crd_b
valid = vertical or horizontal
if valid == False:
print('Invalid length')
return False
if vertical:
waters[y_crd_a][x_crd_a:x_crd_b + 1] = ship[0]
print(waters[y_crd_a][x_crd_a:x_crd_b])
printBoard()
print('X: %s , Y: %s , X: %s , Y: %s' %(x_crd_a,y_crd_a,x_crd_b,y_crd_b))
return True
except ValueError:
print('Error. Try again.')
return False
for ship in ship_type:
while True:
print('Coordinates for %s (%s): ' %(ship[1],ship[2]),end='')
if board_coord_to_npcoord(ship,input()): break
的{{1}}到NaN
的{{1}}以及2015
的{{1}}到2016
提出了<。 / p>
相反,请在China
之后执行2011
2013
USA
您的方法执行了应有的操作。如果采用在现有索引中找到的值并将其传播给所有新索引。
ffill