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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32814746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:56:19  来源:igfitidea点击:

Pandas - create dataframe manually and insert values

pandasdataframemanual

提问by user1700890

Here is my code:

这是我的代码:

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

Here is output:

这是输出:

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

Any suggestions on how to fix it? I do not know overall size of my dataframe before hand, but I can guess.

有关如何修复它的任何建议?我事先不知道我的数据框的整体大小,但我可以猜测。

回答by hellpanderr

You can either initialize dataframe with data using

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

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

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

or use set_valuemethod (which is much faster than ilocby the way): df.set_value(0,'A',5)

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

UPDATE 2018-04-12?

更新 2018-04-12

Since pandas version 0.21.0 df.set_valueis deprecated. You should use .at[]or .iat[]accessors instead:

由于Pandas版本 0.21.0df.set_value已弃用。您应该使用.at[]or.iat[]访问器:

df.at[0, 'A'] = 5

回答by MhP

Providing a sample to increase your data frame dynamically... sizeOfDataFrame variable just limits for loop which adds data to the dataframe and is dynamic...

提供一个示例来动态增加您的数据框... sizeOfDataFrame 变量只是限制循环,它将数据添加到数据框并且是动态的...

import pandas as pd
import numpy as np
yourDataFrame = pd.DataFrame()
sizeOfDataFrame = np.random.randint(100, size=1)
for currentLine in range(sizeOfDataFrame):
    yourDataFrame = yourDataFrame.append(pd.DataFrame({"A":np.random.randint(100, size=1),"B":np.random.randint(100, size=1),"C":np.random.randint(100, size=1)},index=[0]))
yourDataFrame.reset_index(inplace = True)    
yourDataFrame.drop('index',axis=1,inplace=True)