gpt4 book ai didi

python - 将一列数据附加到现有数据框

转载 作者:太空宇宙 更新时间:2023-11-04 09:38:57 24 4
gpt4 key购买 nike

我想将数据列表附加到数据框,以便该列表将出现在列中,即:

#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 个数据帧有什么想法吗?

最佳答案

我认为需要concat包含 A 列的新 DataFrame,然后是 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

关于python - 将一列数据附加到现有数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52437806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com