Tom
Tom

Reputation: 1063

DataFrame.loc produces list object instead of single value

I'm attempting to have my dataframe insert a particular value into a column. The desired value will be the 'Return Weather' where both the 'City' and 'Day' match the specified values. Here's a toy example:

index    City         Weather    Day    Return City    Return Weather
0        New York     65         3      Baltimore         
1        Atlanta      77         6      Chicago        
2        Baltimore    68         9      Orlando        
3        Chicago      62         13     Boston         
4        Boston       57         14     Atlanta       
5        Orlando      88         19     New York
6        Baltimore    59         3      Chicago
7        Chicago      66         6      Atlanta

Here's the code I'm trying:

for i in df.index:
    day = df.loc[i, 'Day']
    rtn_city = df.loc[i, 'Return City']
    df.loc[i, 'Return Weather'] = df.loc[(df['City'] == rtn_city) & (df['Day'] == day), 'Weather'].values

However I get:

ValueError: Must have equal len keys and value when setting with an iterable

If I set the last line to print...

results = df.loc[(df['City'] == rtn_city) & (df['Day'] == day), 'Temp'].values
print(results)

I get the correct answers but they appear to be lists:

[59]

[66]

Which smells like my problem. Any thoughts?

Upvotes: 1

Views: 971

Answers (1)

Karn Kumar
Karn Kumar

Reputation: 8816

With the given index set, we you can directly select rows for different “last_name” values using .loc[] – either singly, or in multiples , for your case..

results = df.loc[[(df['City'] == rtn_city) & (df['Day'] == day), 'Weather']].values 

Or try as suggested @Sai Kumar for particular index..

results = df.loc[(df['City'] == rtn_city) & (df['Day'] == day), 'Weather'].values[0]

Upvotes: 1

Related Questions