如何使用1 for循环语句同时获取值和索引

时间:2019-11-06 14:51:13

标签: python pandas

我有一个数据框,我想使用for循环来获取列值和该值的索引。

下面是数据框,我正在尝试从“日期”列中获取值

enter image description here

下面是我的代码。我声明了一个count变量来跟踪索引。 我的问题:for循环声明中是否可以在一行中获取列值及其索引?

for row in loadexpense_df["Date"]:行中,row是包含date列中值的变量。可以改善for循环以获得值及其索引吗?

谢谢

count =0
load = loadexpense_df["Date"]
for row in loadexpense_df["Date"]:
    checkMonth = row.strftime("%m")

    if checkMonth == '01':
        loadexpense_df["Month"][count] = "Jul"
    elif checkMonth == '02':
        loadexpense_df["Month"][count] = "Aug"
    elif checkMonth == '03':
        loadexpense_df["Month"][count] = "Sep"
    elif checkMonth == '04':

    count = count +1

4 个答案:

答案 0 :(得分:1)

这是一个可以帮助您的示例。

mylist = ["ball","cat","apple"]

for idx, val in enumerate(mylist):
    print ("index is {0} and value is {1}".format(idx, val))

答案 1 :(得分:1)

iterrows返回索引和以行表示为系列的行

for index, row in df.iterrows():

有关更多信息,请参见此处:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html

答案 2 :(得分:1)

这是iteritems的作用:

for idx, val in loadexpense_df['Date'].items():
    pass

但是,您的代码在链索引编制方面可能会遇到一些问题。例如:

loadexpense_df["Month"][count] = "Jul"

我认为您应该查看np.select.loc访问。这有助于提高代码的可读性和性能。例如:

checkMonth = loadexpense_df['Date'].dt.month

loadexpense_df.loc[checkMonth==1, 'month'] = 'Jul'
...

答案 3 :(得分:1)

您必须以“熊猫的方式”思考,并尽可能将循环创建留给熊猫。 解决方案示例:

df
Date  Amount
0 2019-10-25       2
1 2019-10-26       5
2 2019-10-27      52
3 2019-10-28      93
4 2019-10-29      70
5 2019-10-30      51
6 2019-10-31      80
7 2019-11-01      61
8 2019-11-02      52
9 2019-11-03      61

m={10:'jul',11:'aug'}

# The easy way to get the month: dt.month
#df["Month"]= pd.Series.replace(df.Date.dt.month, m)
df["Month"]= df.Date.dt.month.replace(m)

        Date  Amount Month
0 2019-10-25       2   jul
1 2019-10-26       5   jul
2 2019-10-27      52   jul
3 2019-10-28      93   jul
4 2019-10-29      70   jul
5 2019-10-30      51   jul
6 2019-10-31      80   jul
7 2019-11-01      61   aug
8 2019-11-02      52   aug
9 2019-11-03      61   aug