Pandas dataframe, creating multiple lines at once via .loc

I can create a new row in the data frame with .loc():

>>> df = pd.DataFrame({'a':[10, 20], 'b':[100,200]}, index='1 2'.split())
>>> df
    a    b
1  10  100
2  20  200
>>> df.loc[3, 'a'] = 30
>>> df
      a      b
1  10.0  100.0
2  20.0  200.0
3  30.0    NaN

But how can I create more than one row using the same method?

>>> df.loc[[4, 5], 'a'] = [40, 50]
...
KeyError: '[4 5] not in index'

I am familiar with .append (), but I am looking for a way that DOES NOT require creating a new line in the Series before adding it to df.

Desired input:

>>> df.loc[[4, 5], 'a'] = [40, 50]

Required conclusion

      a      b
1  10.0  100.0
2  20.0  200.0
3  30.0    NaN
4  40.0    NaN
5  50.0    NaN

Where the last 2 lines are added.

+6
source share
2 answers

Data examples

>>> data = pd.DataFrame({
    'a': [10, 6, -3, -2, 4, 12, 3, 3], 
    'b': [6, -3, 6, 12, 8, 11, -5, -5], 
    'id': [1, 1, 1, 1, 6, 2, 2, 4]})

Case 1 Note that rangeyou can change the way you want.

>>> for i in range(10):
...     data.loc[i, 'a'] = 30
... 
>>> data
      a     b   id
0  30.0   6.0  1.0
1  30.0  -3.0  1.0
2  30.0   6.0  1.0
3  30.0  12.0  1.0
4  30.0   8.0  6.0
5  30.0  11.0  2.0
6  30.0  -5.0  2.0
7  30.0  -5.0  4.0
8  30.0   NaN  NaN
9  30.0   NaN  NaN

2 , 8 . c 10, NaN.

>>> for i in range(10):
...     data.loc[i, 'c'] = 30
... 
>>> data
      a     b   id     c
0  10.0   6.0  1.0  30.0
1   6.0  -3.0  1.0  30.0
2  -3.0   6.0  1.0  30.0
3  -2.0  12.0  1.0  30.0
4   4.0   8.0  6.0  30.0
5  12.0  11.0  2.0  30.0
6   3.0  -5.0  2.0  30.0
7   3.0  -5.0  4.0  30.0
8   NaN   NaN  NaN  30.0
9   NaN   NaN  NaN  30.0
+1

, , , .

:

  1. :

    import pandas as pd
    df = pd.DataFrame({'a':[10, 20], 'b':[100,200]}, index='1 2'.split())
    df.loc[3, 'a'] = 30
    
  2. df.index, .reindex:

    idx = list(df.index)
    new_rows = list(map(str, range(4, 6)))  # easier extensible than new_rows = ["4", "5"]
    idx.extend(new_rows)
    df = df.reindex(index=idx)
    
  3. .loc:

    df.loc[new_rows, "a"] = [40, 50]
    

    >>> df
          a      b
    1  10.0  100.0
    2  20.0  200.0
    3  30.0    NaN
    4  40.0    NaN
    5  50.0    NaN
    
0

Source: https://habr.com/ru/post/1677412/


All Articles