Dropped because I was addicted to demons.
>>> s1 = pd.Series(data=[10,20,30])
>>> s1
0 10
1 20
2 30
dtype: int64
>>> s2 = pd.Series(data=[100,200,300])
>>> s2
0 100
1 200
2 300
dtype: int64
Two Series are added as a column of DataFrame.
>>> df = pd.DataFrame()
>>> df[1]=s1
>>> df[2]=s2
>>> df
1 2
0 10 100
1 20 200
2 30 300
This is easy.
>>> s1 = pd.Series(data=[10,20,30], index=[1,2,3])
>>> s1
1 10
2 20
3 30
dtype: int64
>>> s2 = pd.Series(data=[100,200,300], index=[2,3,4])
>>> s2
2 100
3 200
4 300
dtype: int64
The indexes of s1 and s2 are not from 0, and there are some things that are not in common.
At this time, if you add it to the DataFrame as before
>>> df[1]=s1
>>> df[2]=s2
>>> df
1 2
0 NaN NaN
1 10.0 NaN
2 20.0 100.0
With a fixed number, it will enter from 0 without permission.
If the original s1 [3] wants to see it and tries to see the contents of df forcibly, an error will occur.
>>> s1[3]
30
>>> df[1][3]
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pandas/core/series.py", line 603, in __getitem__
result = self.index.get_value(self, key)
File "/usr/local/lib/python2.7/dist-packages/pandas/indexes/base.py", line 2169, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/index.pyx", line 98, in pandas.index.IndexEngine.get_value (pandas/index.c:3557)
File "pandas/index.pyx", line 106, in pandas.index.IndexEngine.get_value (pandas/index.c:3240)
File "pandas/index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)
File "pandas/src/hashtable_class_helper.pxi", line 404, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:8564)
File "pandas/src/hashtable_class_helper.pxi", line 410, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:8508)
KeyError: 3
In this case, use `` `pandas.concat```.
>>> df = pd.DataFrame()
>>> df = pd.concat([df, s1], axis=1)
>>> df
0
1 10
2 20
3 30
>>> df = pd.concat([df, s2], axis=1)
>>> df
0 0
1 10.0 NaN
2 20.0 100.0
3 30.0 200.0
4 NaN 300.0
If you put axis = 1
in the argument, it will be added in the column direction. Also, `` `numpy.nan``` is entered where there is none.
** However, column becomes 0. ** ** It seems that it cannot be specified by an argument, so first set Series to a one-dimensional DataFrame and then concat.
>>> df = pd.DataFrame()
>>> df = pd.concat([df, pd.DataFrame(s1, columns=[1])], axis=1)
>>> df = pd.concat([df, pd.DataFrame(s2, columns=[2])], axis=1)
>>> df
1 2
1 10.0 NaN
2 20.0 100.0
3 30.0 200.0
4 NaN 300
Recommended Posts