Pandas- 将值设置为空数据框 [英] Pandas- set values to an empty dataframe

查看:107
本文介绍了Pandas- 将值设置为空数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经初始化了一个空的 Pandas 数据框,我现在正试图填充它,但我一直遇到同样的错误.这是我正在使用的(简化)代码

I have initialized an empty pandas dataframe that I am now trying to fill but I keep running into the same error. This is the (simplified) code I am using

import pandas as pd
cols = list("ABC")
df = pd.DataFrame(columns=cols)
# sett the values for the first two rows
df.loc[0:2,:] = [[1,2],[3,4],[5,6]]

运行上述代码时出现以下错误:

On running the above code I get the following error:

ValueError: cannot copy sequence with size 3 to array axis with dimension 0

我不确定这是什么原因.我一次使用一行进行了相同的尝试,并且可以正常工作(df.loc[0,:] = [1,2,3]).当我想处理多行时,我认为这应该是逻辑扩展.但很明显,我错了.这样做的正确方法是什么?我需要为多行和多列输入一次值.我可以使用循环来完成,但这不是我想要的.

I am not sure whats causing this. I tried the same using a single row at a time and it works (df.loc[0,:] = [1,2,3]). I thought this should be the logical expansion when I want to handle more than one rows. But clearly, I am wrong. Whats the correct way to do this? I need to enter values for multiple rows and columns and once. I can do it using a loop but that's not what I am looking for.

任何帮助都会很棒.谢谢

Any help would be great. Thanks

推荐答案

由于您拥有空数据帧中的列,因此请在数据帧构造函数中使用它,即

Since you have the columns from empty dataframe use it in dataframe constructor i.e

import pandas as pd
cols = list("ABC")
df = pd.DataFrame(columns=cols)

df = pd.DataFrame(np.array([[1,2],[3,4],[5,6]]).T,columns=df.columns) 

   A  B  C
0  1  3  5
1  2  4  6

好吧,如果您想专门使用 loc,请先重新索引数据帧,然后分配即

Well, if you want to use loc specifically then, reindex the dataframe first then assign i.e

arr = np.array([[1,2],[3,4],[5,6]]).T
df = df.reindex(np.arange(arr.shape[0]))
df.loc[0:arr.shape[0],:] = arr

   A  B  C
0  1  3  5
1  2  4  6

这篇关于Pandas- 将值设置为空数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆