Python pandas:逐行填充数据帧

时间:2013-06-13 16:02:32

标签: python dataframe row pandas

pandas.DataFrame对象添加行的简单任务似乎很难实现。有3个与此相关的stackoverflow问题,其中没有一个给出了有效的答案。

这是我正在尝试做的事情。我有一个DataFrame,我已经知道了形状以及行和列的名称。

>>> df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'])
>>> df
     a    b    c    d
x  NaN  NaN  NaN  NaN
y  NaN  NaN  NaN  NaN
z  NaN  NaN  NaN  NaN

现在,我有一个迭代计算行值的函数。如何使用字典或pandas.Series填写其中一行?以下是失败的各种尝试:

>>> y = {'a':1, 'b':5, 'c':2, 'd':3} 
>>> df['y'] = y
AssertionError: Length of values does not match length of index

显然它试图添加一列而不是一行。

>>> y = {'a':1, 'b':5, 'c':2, 'd':3} 
>>> df.join(y)
AttributeError: 'builtin_function_or_method' object has no attribute 'is_unique'

非常无法提供信息的错误消息。

>>> y = {'a':1, 'b':5, 'c':2, 'd':3} 
>>> df.set_value(index='y', value=y)
TypeError: set_value() takes exactly 4 arguments (3 given)

显然,这仅用于在数据框中设置单个值。

>>> y = {'a':1, 'b':5, 'c':2, 'd':3} 
>>> df.append(y)
Exception: Can only append a Series if ignore_index=True

好吧,我不想忽略索引,否则结果如下:

>>> df.append(y, ignore_index=True)
     a    b    c    d
0  NaN  NaN  NaN  NaN
1  NaN  NaN  NaN  NaN
2  NaN  NaN  NaN  NaN
3    1    5    2    3

它确实将列名称与值对齐,但丢失了行标签。

>>> y = {'a':1, 'b':5, 'c':2, 'd':3} 
>>> df.ix['y'] = y
>>> df
                                  a                                 b  \
x                               NaN                               NaN
y  {'a': 1, 'c': 2, 'b': 5, 'd': 3}  {'a': 1, 'c': 2, 'b': 5, 'd': 3}
z                               NaN                               NaN

                                  c                                 d
x                               NaN                               NaN
y  {'a': 1, 'c': 2, 'b': 5, 'd': 3}  {'a': 1, 'c': 2, 'b': 5, 'd': 3}
z                               NaN                               NaN

那也悲惨地失败了。

那你怎么做的?

5 个答案:

答案 0 :(得分:70)

df['y']会设置一列

由于您要设置行,请使用.loc

请注意,.ix在此处是等效的,因为您尝试分配字典,因此失败了 行y的每个元素可能不是你想要的;转换为系列告诉熊猫 您想要对齐输入(例如,您不必指定所有元素)

In [7]: df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'])

In [8]: df.loc['y'] = pandas.Series({'a':1, 'b':5, 'c':2, 'd':3})

In [9]: df
Out[9]: 
     a    b    c    d
x  NaN  NaN  NaN  NaN
y    1    5    2    3
z  NaN  NaN  NaN  NaN

答案 1 :(得分:54)

我的方法是,但我不能保证这是最快的解决方案。

df = pd.DataFrame(columns=["firstname", "lastname"])
df = df.append({
     "firstname": "John",
     "lastname":  "Johny"
      }, ignore_index=True)

答案 2 :(得分:21)

这是一个更简单的版本

Create Table #PersonIDs (PersonID int Not Null Primary Key Clustered);

Insert Into #PersonIDs 
Select Person.ID --- of those rows only where we have CA in RentedHouseDetails

Insert Into CALIFORNIAHOUSE
Select PersonID From #PersonIDs;

Insert Into STATUSGREEN
Select PersonID From #PersonIDs;

Update rhd
   Set ISOK = 'No'
   From RentedHousesDetail As rhd
   Join #PersonIDs On rhd.PersonID = #PersonIDs.PersonID;

Drop Table #PersonIDs;

答案 3 :(得分:13)

如果您的输入行是列表而不是字典,那么以下是一个简单的解决方案:

import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])

pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
#    A  B  C
# 0  1  2  3
# 1  4  5  6

答案 4 :(得分:0)

代码背后的逻辑非常简单明了

使用字典制作 1 行的 df

然后创建一个形状为 (1, 4) 的 df,它只包含 NaN 并且与字典键具有相同的列

然后将一个 nan df 与 dict df 和另一个 nan df 连接起来

import pandas as pd
import numpy as np

raw_datav = {'a':1, 'b':5, 'c':2, 'd':3} 

datav_df = pd.DataFrame(raw_datav, index=[0])

nan_df = pd.DataFrame([[np.nan]*4], columns=raw_datav.keys())

df = pd.concat([nan_df, datav_df, nan_df], ignore_index=True)

df.index = ["x", "y", "z"]

print(df)

给予

a    b    c    d
x  NaN  NaN  NaN  NaN
y  1.0  5.0  2.0  3.0
z  NaN  NaN  NaN  NaN

[Program finished]
相关问题