list1 = [A1, A2, A3, A4, A5, A7, A8]
找到丢失的字符并将其重新应用到列表中。然后获取该列表并将其插入到pandas数据框中。
我把它分成三个功能:
remove_chars
missing_elements
查找列表中缺少的任何数字,并生成这些数字的新列表(在
list1
上面,
缺少元素
会回来的
[6]
insert_into_df
使用来自
将丢失的数字粘贴到数据帧中它们应该位于的位置(数据帧有一组列,这些列被标记为
列表1
它可能缺少列)。下面是它的样子:
# Function to remove strings from questions
# Input list of strings and ints and outputs list with only ints
def remove_chars(L1):
if len(L1) > 0:
for i, j in enumerate(L1):
L1[i] = re.sub('[^0-9]','', j)
L1[i] = int(L1[i])
return L1
else:
return
# Function to pick out missing numbers in lists
# This is used to ensure that each column list contains no deleted columns
def missing_elements(L1, start = None, end = None):
if end is None and start is None:
if len(L1) > 0:
newlist1 = remove_chars(L1)
start = 0
end = len(newlist1) - 1
else:
return
start, end = newlist1[0], newlist1[-1]
return sorted(set(range(start, end + 1)).difference(newlist1))
# Function to insert missing sequential columns into dataframe
def insert_into_df(L, df):
"""
insert_into_df: Inserts columns missing from dataframes into dataframe at the
proper index so that the inserted columns are in the correct order. This
function is only to be used for dataframes containing sequential columns.
----
Parameters:
L: The list of column names that may contain a missing column
df: The dataframe into which these columns will be inserted
"""
tempList = list(L)
if len(L) > 0:
stringL0 = str(re.sub(r'\d+', '', tempList[0]))
mList1 = missing_elements(L)
if len(mList1) > 0:
for i in range(len(mList1)):
df.insert(loc = mList1[i], column = stringL0 + str(mList1[i]), value = 0)
else:
return df
return df
else:
return df
当我输入print语句时,它似乎输出了正确的数据帧,但是在将其导出为csv时,它似乎已经应用了
移除字符
函数指向每个列标题,并按顺序输出一组数字。
有谁能告诉我为什么会发生这种事以及该怎么办吗?如果你需要更多的澄清,请告诉我。