>> import pandas as pd >>> df = pd.DataFrame({-6ren">
gpt4 book ai didi

python - 如何使用 "loc"和 "for"在 pandas 中添加行?

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:46 24 4
gpt4 key购买 nike

我想通过“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]'

但是下面的代码是成功的。

>>> df_new.loc[1] = df.loc[1]
>>> df_new
A
1 1.2

最佳答案

为什么不看看 for 在这里迭代了什么?

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

关于python - 如何使用 "loc"和 "for"在 pandas 中添加行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47768590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com