我想将数据列表追加到数据框,以便该列表出现在列中,即:
#Existing dataframe:
[A, 20150901, 20150902
1 4 5
4 2 7]
#list of data to append to column A:
data = [8,9,4]
#Required dataframe
[A, 20150901, 20150902
1 4 5
4 2 7
8, 0 0
9 0 0
4 0 0]
我正在使用以下内容:
df_new = df.copy(deep=True)
#I am copying and deleting data as column names are type Timestamp and easier to reuse them
df_new.drop(df_new.index, inplace=True)
for item in data_list:
df_new = df_new.append([{'A':item}], ignore_index=True)
df_new.fillna(0, inplace=True)
df = pd.concat([df, df_new], axis=0, ignore_index=True)
但是循环执行此操作效率低下,而且我得到以下警告:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.
关于如何克服此错误并一次性添加2个数据框的任何想法?
答案 0 :(得分:2)
我认为需要concat
个新的DataFrame,其列为A
,然后如果想要相同的列顺序,则需要reindex
,最后用fillna
替换缺失的值:
data = [8,9,4]
df_new = pd.DataFrame({'A':data})
df = (pd.concat([df, df_new], ignore_index=True)
.reindex(columns=df.columns)
.fillna(0, downcast='infer'))
print (df)
A 20150901 20150902
0 1 4 5
1 4 2 7
2 8 0 0
3 9 0 0
4 4 0 0
答案 1 :(得分:1)
我想,你可以做这样的事情。
df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame({'A':[8,9,4]})
df.append(df2).fillna(0)
A B
0 1 2.0
1 3 4.0
0 8 0.0
1 9 0.0
2 4 0.0
答案 2 :(得分:0)
也许您可以通过以下方式做到这一点:
function AsDownload() {
window.open("https://alexanderhawking.itch.io/asteroid-racer", "_blank");
};