存储DataFrame行中的值,并在另一个操作中使用它们



我有一个DataFrame,我从CSV文件中读取,我想将DataFrame中的行中的单个值存储在一些变量中。我想在另一个步骤中使用DataFrame的值来执行另一个操作。请注意,我不希望结果是级数,而是整数之类的值。我还在学习,但我无法理解我所咨询的资源。提前谢谢你。

3

有很多方法可以做到这一点,但一个简单的方法是使用index方法。其他人可能会给出其他方法,我在这里举例说明index方法。我将创建一个字典,并将其更改为DataFrame,从中可以执行行迭代。

# Start by importing pandas as pd
import pandas as pd
# Proceed by defining a dictionary that contains a player's stats (just for 
ilustration, not real data)
myData = {'Football Club': ['Chelsea', 'Man Utd', 'Inter Milan', 'Everton'],
'Matches Played': [2, 32, 36, 37],
'Goals Scored': [1, 12, 24, 25],
'Assist Given': [0, 0, 11, 6],
'Red card': [0,0,0,0,],
'Yellow Card':[0,4,4,3]}
# Next create a DataFrame from the dictionary from previous step
df = pd.DataFrame(myData, columns = ['Football Club', 'Matches Played', 'Goals 
Scored', 'Red card', 'Yellow Card'])

#See what the data look like.
print("This is the created Dataframe from the dictionary:n", df)
print("n Now, you can iterate over selected rows or all the rows using 
index 
attribute as follows:n")
#Store the values in variables
for indIte in df.index:
clubs=df['Football Club'][indIte]
goals =df['Goals Scored'][indIte]
matches=df['Matches Played'][indIte]
#To see the results that can be used later in the same program
print(clubs, matches, goals)
#You will get the following results:
This is the created Dataframe from the dictionary :
Football Club  Matches Played  Goals Scored  Red card  Yellow Card
0       Chelsea               2             1         0            0
1       Man Utd              32            12         0            4
2   Inter Milan              36            24         0            4
3       Everton              37            25         0            3
Now, you can iterate over selected rows or all the rows using index 
attribute as follows:
Chelsea 2 1
Man Utd 32 12
Inter Milan 36 24
Everton 37 25

使用说明:

x, y, z = df.to_dict(orient='list').values()
>>> x
[1, 3, 4]
>>> y
[2, 2, 5]
>>> z
[3, 1, 6]

df.values是数据帧的numpy数组。因此,您可以为后续处理操作df.values

最新更新