gpt4 book ai didi

python - 使用 iterrows(),从数据帧的单行中插入列的子集作为另一个数据帧中的新行

转载 作者:行者123 更新时间:2023-12-01 09:09:21 26 4
gpt4 key购买 nike

我需要从 6 列数据帧的单行中选择 3 列,并将其附加到另一个只有 3 列的数据帧。

import pandas
import numpy

df1 = pd.DataFrame({'Name':['Sanjay','Robin','Hugo'],
'Email':['s@email.com','r@email.com','h@email.com'],
'OrderNo':[23,234,66],
'Address':['234 West Ave','45 Oak Street','Rt. 3443 FM290'],
'Phone':['555-1212','555-3322','555-6655'],
'Age':[34,23,65]})

df2 = pd.DataFrame(columns = ['Name', 'OrderNo', 'Phone'])

for index, row in df1.iterrows():
if index == 0:
df2 = df2.append(row[0,2,4])
#df2 = df2.append(row['Name','OrderNo','Phone']) <------also threw key error

print(df2)

这是我希望看到的:

     Name  OrderNo     Phone
0 Sanjay 23 555-1212

以下是本练习的输出:

Traceback (most recent call last):
File "/Users/Joe/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3109, in get_value
return libindex.get_value_box(s, key)
File "pandas/_libs/index.pyx", line 55, in pandas._libs.index.get_value_box
File "pandas/_libs/index.pyx", line 63, in pandas._libs.index.get_value_box
TypeError: 'tuple' object cannot be interpreted as an integer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 15, in <module>
File "/Users/Joe/anaconda3/lib/python3.6/site-packages/pandas/core/series.py", line 766, in __getitem__
result = self.index.get_value(self, key)
File "/Users/Joe/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3117, in get_value
raise e1
File "/Users/Joe/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3103, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/_libs/index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 114, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: (0, 2, 4)

最佳答案

您还可以使用 DataFrame.append() 函数:

df2=df2.append(df1[['Name', 'OrderNo', 'Phone']].iloc[0])
df2

Name OrderNo Phone
0 Sanjay 23 555-1212

关于python - 使用 iterrows(),从数据帧的单行中插入列的子集作为另一个数据帧中的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51797491/

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