pandas 如何向现有 Dataframe 添加新数据

yzuktlbb  于 2022-12-02  发布在  其他
关注(0)|答案(2)|浏览(313)

I've created empty dataframe that I have to fill.

d = {'A': [], 'B': [], 'C': []}
dataframe = pd.DataFrame(data=d)

Then I am assigning data like this:

dataframe['A'] = some_list_1a
dataframe['B'] = some_list_1b
dataframe['C'] = some_list_1c

So my dataframe is filled like this:

A      B     C
----------------
val1  val1  val1
val1  val1  val1
val1  val1  val1

Then I have to add new values from list but the previous way is not working: dataframe['A'] = some_list_2a etc.
That's what I want:

A      B     C
----------------
val1  val1  val1
val1  val1  val1
val1  val1  val1
val2  val2  val2
val2  val1  val2
val2  val2  val2

(val1 - values from first lists, val2 - values from second lists)
I know I can make second dataframe and use concat method, but is there another way of doing it?

ymzxtsji

ymzxtsji1#

首先使用所有联接列表创建字典,然后调用DataFrame是最快的推荐方法,请检查this

d = {'A': some_list_1a + some_list_2a, 
     'B': some_list_1b + some_list_2b,
     'C': some_list_1c + some_list_2c}
dataframe = pd.DataFrame(data=d)

如果需要在循环中追加列表的字典:

from collections import defaultdict

d = defaultdict(list)

#some loop
for x in iter:
    d[col_name].append(sublist)
    
dataframe = pd.DataFrame(data=d)
vlf7wbxs

vlf7wbxs2#

append()函数用于将其他 Dataframe 的行附加到给定 Dataframe 的末尾,返回一个新的 Dataframe 对象。不在原始 Dataframe 中的列将作为新列添加,新单元格将用NONE值填充。

相关问题