簡體   English   中英

從 DataFrame 中檢索值

[英]Retrieving values from a DataFrame

我的 DataFrame ( df = df.sort_values('market_name').iloc[:1] ):

                  competition                         event_name  event_id country_code           market_name    market_id  total_matched             Home  Home_id            Away  Away_id Draw  Draw_id
7  CONMEBOL Copa Libertadores  Atletico MG v Independiente (Ecu)  31459931         None  First Half Goals 1.5  1.199224510  115362.090985  Under 1.5 Goals  1221385  Over 1.5 Goals  1221386             0

對於獲取market_id我需要使用索引[0]

df['market_id'].values[0]

要收集僅寫入['market_id']的值,我正在使用.reset_index() + .iterrows()

df = df.sort_values('market_name').iloc[:1]
df = df.reset_index()
for index, row in df.iterrows():
    row['market_id']

由於這個dataframe將始終只存在一行,有沒有更專業的方法來獲得相同的結果,而無需使用多行和循環來實現這一混亂?

我的想法是預先格式化這個dataframe所以我不需要把這個.value[0]放在我想要獲取的每個值中並且只通過列名調用。

將單行 dataframe 轉換為字典 python 怎么樣? 你可以這樣做:

dct = df.to_dict(orient='records')[0];
marketId = dct['market_id']

如果你想在修改后把字典改回一個dataframe,你可以這樣做:

df2 = pd.DataFrame([dct], columns=dct.keys())

或者,由於您的數據是一維的,您可以使用 pandas 系列而不是 Dataframe:

ser = df.reset_index(drop=True).T[0]
print(ser)
print('\nmarket_id is:', ser['market_id'])

Output:

competition             CONMEBOL Copa Libertadores
event_name       Atletico MG v Independiente (Ecu)
event_id                                  31459931
country_code                                  None
market_name                   First Half Goals 1.5
market_id                                 1.199225
total_matched                        115362.090985
Home                               Under 1.5 Goals
Home_id                                    1221385
Away                                Over 1.5 Goals
Away_id                                    1221386
Draw
Draw_id                                          0
Name: 0, dtype: object

market_id is: 1.19922451

如果您使用.iloc[0]而不是.iloc[:1]那么您將獲得單行pandas.Series並且您可以僅使用 header 從Series中獲取價值。這不需要.reset_index()

import pandas as pd

data = {
    'A': [1,2,3], 
    'B': [4,5,6], 
    'C': [7,8,9]
}

df = pd.DataFrame(data)

row = df.sort_values('A').iloc[0]

print('row:')
print(row)
print('---')
print('value A:', row['A'])
print('value B:', row['B'])

結果:

row:
A    1
B    4
C    7
Name: 0, dtype: int64
---
value A: 1
value B: 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM