【问题标题】:populating empty dataframe from a list in python从python中的列表填充空数据框
【发布时间】:2020-08-05 05:03:09
【问题描述】:

我需要从列表中填充数据框。

lst=[1,"name1",10,2,"name2",2,"name2",20,3]
df=pd.DataFrame(columns=['a','b','c'])
j=0
for i in range(len(list(df.columns))-1):

   for t,v in enumerate(lst):
       col_index=j%3
       df.iloc[i,col_index]=lst[t]
       j=j+1

上面的代码给了我一个错误。

我希望 df 关注

a  b     c
1  name1 10
2  name2  20
3  NaN    NaN

我已经尝试过了,但它给了我以下错误 IndexError :单个位置索引器超出范围

【问题讨论】:

  • 那么错误是什么?请分享。
  • 我已经更新了错误..这是一个索引错误..它基本上不允许我从列表中分配一个值
  • 错误是,当df 为空时,您正试图通过索引从中获取项目。这就像尝试 foo[5]foo 是一个空列表。
  • 你能解释一下lst吗?比如它的模式是什么?不应该是lst=[1,"name1",10,2,"name2",20]吗?
  • 基本上 len(lst) 不一定能被 3 整除...所以它的计数可以不是 3 的倍数

标签: python pandas


【解决方案1】:

创建字典列表[{key:value, key:value}, {key:value, key:value}, {key:value, key:value}]

将此直接添加为数据框。您还可以通过创建函数并在构建字典时向其传递数据来控制以这种方式添加的内容。

如果行与列的顺序始终正确,则可以使用 itertools 循环实现此目的。

我认为3, name3, 30 不正确,我认为您应该拥有的列表应该是这样的。

cols = ['a','b','c']
rows = [1, "name1", 10, 2,"name2", 20, 3, "name3", 30]

并使用 itertools 的强大功能 https://docs.python.org/3/library/itertools.html#itertools.cycle

cycle('abc') --> a b c a b c a b c a b c ...

我认为这段代码可以帮助你。

import itertools

def parse_data(data):
    if data:
        pass
        #do something.
    return data

cols = ['a','b','c']
rows = [1, "name1", 10, 2,"name2", 20, 3, "name3", 30]

d = [] # Temp list for dataframe to hold the dictionaries of data.
e = {} # Temp dict to fill rows & cols for each cycle.

for x, y in zip(itertools.cycle(cols), rows): # cycle through the cols but not the rows. 

    y = parse_data(y) # do any filtering or removals here. 

    if x == cols[0]: # the first col triggers the append and reset of the dictionary
        e = {x:y}  # re init the temp dictionary      
        d.append(e)  # append to temp df list
    else:
        e.update({x:y}) # add other elements
    print(e)
    print(d)

df=pd.DataFrame(d) # create dataframe
print(df)

"""
  a     b   c
  1  name1  10
  2  name2  20
  3  name3  30

""""

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    相关资源
    最近更新 更多