简体   繁体   中英

Appending a Pandas Series as a row in a DataFrame, ignoring non-matching columns

Let's say I have the following Pandas Dataframe, with no rows yet:

'Jeep' | 'Volvo' | 'Honda'
--------------------------

I have the following Pandas Series:

Honda    5
Nissan   3
Jeep     7
Toyota   2

I want to add this series as a row (not including elements that don't match a column name)

Result:

'Jeep' | 'Volvo' | 'Honda'
----------------------------
   7   |    0    |    5

Is it possible to do this?

import pandas as pd
df = pd.DataFrame(columns=['Jeep', 'Volvo', 'Honda'])  
s = pd.Series({"Honda": 5, "Nissan": 3, "Jeep": 7, "Toyota": 2})  

df.append(s[df.columns], ignore_index=True).fillna(0)

You can use append than get the specific columns:

>>> import pandas as pd
>>> df = pd.DataFrame(columns=['Jeep', 'Volvo', 'Honda'])
>>> s = pd.Series([5, 3, 7, 2],index=['Honda', 'Nissan', 'Jeep', 'Toyota'])
>>> df1 = df.append(s, ignore_index=True)
>>> df1[df.columns].fillna(0)
   Jeep  Volvo  Honda
0   7.0    0.0    5.0
>>> 

This code is virtually:

>>> df1 = df.append(s, ignore_index=True)
>>> df1[df.columns].fillna(0)
   Jeep  Volvo  Honda
0   7.0    0.0    5.0
>>> 

You can use reindex in a couple of different ways outlined below.

series.to_frame().T.reindex(df.columns, axis=1, fill_value=0)

   Jeep  Volvo  Honda
0     7      0      5

series.reindex(df.columns, fill_value=0).to_frame().T

   Jeep  Volvo  Honda
0     7      0      5

df.append(series.reindex(df.columns, fill_value=0).rename(len(df)))

  Jeep Volvo Honda
0    7     0     5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM