首页 > 解决方案 > 在 Pandas 中从 read_excel 设置 Python 变量

问题描述

我觉得这是一件很简单的事情,但是,我无可救药地卡住了。我有一个excel df,我想循环并从中获取值来创建一个对象。

cols = ['Net Transaction Amount', 'Original Value Transacted', 'First Name', 'Last 
Name', 'Email', 'Transaction Date', 'Card Number', 'Card Expiration Date', 
'Transaction Custom String1', 'Stripe ID', 'Payment Method', 'Total To-Date Gift 
Amount', 'Start Date', 'Next Payment Date',]
bb_cus = pd.read_excel(loc,usecols=cols, header=0)

#for i in bb_cus:
#name = bb_cus['First Name'] +' '+ bb_cus['Last Name']

#print(name)
print(bb_cus)

这是输出:

     Net Transaction Amount  ...   Next Payment Date
0                         5  ... 2020-12-12 04:05:00
1                        50  ... 2020-12-12 04:32:00
2                        10  ... 2020-12-12 07:13:00
3                        10  ... 2020-12-12 06:47:00
4                         5  ... 2020-12-12 08:26:00
...                     ...  ...                 ...
3593                     10  ... 2020-12-01 13:48:00
3594                     10  ... 2020-12-09 14:45:00
3595                     10  ... 2020-11-14 11:29:00
3596                    100  ... 2020-11-27 23:07:00
3597                  Total  ...                 NaT

[3598 rows x 14 columns]

我希望能够使用循环从每一行中获取值,以在我的数据库中创建一个新的客户对象。像这样的东西:

for i in bb_cus:
name = bb_cus['First Name']

print(name)

从这里我得到这个。但我不明白如何获得名称:

for i in bb_cus:
    name = bb_cus['First Name']

    print(name)


    3597        NaN
    Name: First Name, Length: 3598, dtype: object
    0        Dianne
    1          Jeff
    2       Shawnna
    3         Roman
    4          Geri
     ...
    3593    Richard
    3594    Dezerae
    3595      Amiya
    3596    Michael
    3597        NaN

如何仅将名称作为字符串而不是新数据对象获取

标签: pythonpandas

解决方案


在 Pandas 中,您使用以下方法迭代行.iterrows()

for i, row in bb_cus.iterrows():
    name = row['First Name']
    print(name)

推荐阅读