Python 如何使用“熊猫”在熊猫中添加行;loc";及;为了“什么?”;?

Python 如何使用“熊猫”在熊猫中添加行;loc";及;为了“什么?”;?,python,pandas,for-loop,Python,Pandas,For Loop,我想通过“loc”将数据帧的数据添加到新的数据帧中。我使用了“loc”,但出现了一个错误。我可以添加数据吗 >>> import pandas as pd >>> df = pd.DataFrame({'A': [1.0, 1.2, 3.4, 4.1, 8.2]}) >>> import pandas as pd >>> df_new = pd.DataFrame(columns=['A']) >>>

我想通过“loc”将数据帧的数据添加到新的数据帧中。我使用了“loc”,但出现了一个错误。我可以添加数据吗

>>> import pandas as pd    
>>> df = pd.DataFrame({'A': [1.0, 1.2, 3.4, 4.1, 8.2]})
>>> import pandas as pd
>>> df_new = pd.DataFrame(columns=['A'])
>>> for i in df:
...     df_new.loc[i] = df.loc[i]
... 
Traceback (most recent call last):
  File "/Users/Hajime/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 1434, in _has_valid_type
    error()
  File "/Users/Hajime/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 1429, in error
    (key, self.obj._get_axis_name(axis)))
KeyError: 'the label [A] is not in the [index]'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/Users/Hajime/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 1328, in __getitem__
    return self._getitem_axis(key, axis=0)
  File "/Users/Hajime/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 1551, in _getitem_axis
    self._has_valid_type(key, axis)
  File "/Users/Hajime/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 1442, in _has_valid_type
    error()
  File "/Users/Hajime/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 1429, in error
    (key, self.obj._get_axis_name(axis)))
KeyError: 'the label [A] is not in the [index]'

为什么不看看这里迭代的是什么

In [353]: for i in df:
     ...:     print(i)
     ...:     
A
结论-对
df
的迭代会导致对列名的迭代。您要查找的是类似于
df.iterrows
,或者在
df.index
上迭代的内容

比如说,

for i, r in df.iterrows():
     df_new.loc[i, :] = r

df_new

     A
0  1.0
1  1.2
2  3.4
3  4.1
4  8.2

错误在这一部分:

for i in df:
    df_new.loc[i] = df.loc[i]
对于loc,第一个参数是索引。但是i是一个列名

如果您只想将df添加到df_new。使用concat

df_new = pd.concat([df_new, df])
只是加上:,然后我会先做你想做的事

df.loc[index of row, column name] 
现在你做错了什么?您正在将列名作为不存在的行索引传递

df_new.loc[:,i] = df.loc[:,i]
不管怎样,您都可以通过一个go中的所有列:

df_new[col_names]=df[col_names]

col_names是一个列表

这不是一个很好的例子,你可以这样做:
df_new=df.copy()
如果答案对你有帮助,请回答。谢谢。对不起,打错了-意思是“列名”,而不是“行”。但是代码片段从一开始就说明了我的意思。
df_new.loc[:,i] = df.loc[:,i]
df_new[col_names]=df[col_names]