Pandas - 手动创建数据框并插入值

use*_*890 7 manual dataframe pandas

这是我的代码:

import pandas as pd
df = pd.DataFrame(columns = ["A", "B"])
df.iloc[0]['A'] = 5
Run Code Online (Sandbox Code Playgroud)

这是输出:

Traceback (most recent call last):
  File "K:/Dop/Pentas/Simpletest/Temp.py", line 38, in <module>
    df.iloc[0]['A'] = 5
  File "C:\Python34\lib\site-packages\pandas\core\indexing.py", line 1189, in __getitem__
    return self._getitem_axis(key, axis=0)
  File "C:\Python34\lib\site-packages\pandas\core\indexing.py", line 1480, in _getitem_axis
    return self._get_loc(key, axis=axis)
  File "C:\Python34\lib\site-packages\pandas\core\indexing.py", line 89, in _get_loc
    return self.obj._ixs(key, axis=axis)
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 1719, in _ixs
    label = self.index[i]
  File "C:\Python34\lib\site-packages\pandas\core\index.py", line 1076, in __getitem__
    return getitem(key)
IndexError: index 0 is out of bounds for axis 0 with size 0
Run Code Online (Sandbox Code Playgroud)

有关如何解决它的任何建议?我不知道我的数据帧的整体大小,但我可以猜测.

hel*_*err 15

您可以使用数据初始化数据框

df = pd.DataFrame(columns=["A", "B"], data=[[5,np.nan]]),

或使用set_value方法(比iloc顺便快得多): df.set_value(0,'A',5)

更新 2018-04-12⬇

由于pandas版本0.21.0 df.set_value已折旧.您应该使用.at[].iat[]访问者:

df.at[0, 'A'] = 5
Run Code Online (Sandbox Code Playgroud)