Is it possible to assign a Series to a DataFrame and use the Series' name as column name?
Question:
Given a Series s
like this:
0 6
1 0
2 0
3 8
4 8
5 10
6 10
7 9
Name: my_series, dtype: int64
and given a df
, would it be possible to assign the series to the df
without having
to specify a column name? (The Series name would be used instead)
So, I’d like to avoid having to do this explicitly:
df['my_series'] = s # avoid
My mind goes to something like this:
pd.concat([df, s.to_frame()], axis=1)
but I guess it is counterintuitive.
I have also thought of using df.assign
, but I think it requires specifying a column name as well.
Answers:
You can try using pandas.Series.name
in the first solution:
df[s.name] = s
# or df.assign(**{s.name: s})
Note that this will override the column if the column with the same name is already present (unlike the pd.concat
solution).
Another option – df.join
:
df = df.join(s)
This one will throw in case of column with same name being present.
Use DataFrame.join
:
df = pd.DataFrame({'col_name':['12','13','14']})
s = pd.Series([0,1,2], name='my_series')
df = df.join(s)
print (df)
col_name my_series
0 12 0
1 13 1
2 14 2
df.insert(1,"my_series",s)
Insert function enables to insert column into DataFrame at specified location, first argument shows where to insert a column second means column name and last your list or series
Given a Series s
like this:
0 6
1 0
2 0
3 8
4 8
5 10
6 10
7 9
Name: my_series, dtype: int64
and given a df
, would it be possible to assign the series to the df
without having
to specify a column name? (The Series name would be used instead)
So, I’d like to avoid having to do this explicitly:
df['my_series'] = s # avoid
My mind goes to something like this:
pd.concat([df, s.to_frame()], axis=1)
but I guess it is counterintuitive.
I have also thought of using df.assign
, but I think it requires specifying a column name as well.
You can try using pandas.Series.name
in the first solution:
df[s.name] = s
# or df.assign(**{s.name: s})
Note that this will override the column if the column with the same name is already present (unlike the pd.concat
solution).
Another option – df.join
:
df = df.join(s)
This one will throw in case of column with same name being present.
Use DataFrame.join
:
df = pd.DataFrame({'col_name':['12','13','14']})
s = pd.Series([0,1,2], name='my_series')
df = df.join(s)
print (df)
col_name my_series
0 12 0
1 13 1
2 14 2
df.insert(1,"my_series",s)
Insert function enables to insert column into DataFrame at specified location, first argument shows where to insert a column second means column name and last your list or series