@@ -1771,30 +1771,40 @@ Key Points:
17711771* This behavior is consistent across df[col] = series and df.loc[:, col] = series
17721772
17731773Examples:
1774- .. ipython :: python
1774+ ~~~~~~~~~
17751775
1776- import pandas as pd
1776+ .. ipython :: python
17771777
17781778 # Create a DataFrame
17791779 df = pd.DataFrame({' values' : [1 , 2 , 3 ]}, index = [' x' , ' y' , ' z' ])
1780+ df
17801781
17811782 # Series with matching indices (different order)
17821783 s1 = pd.Series([10 , 20 , 30 ], index = [' z' , ' x' , ' y' ])
17831784 df[' aligned' ] = s1 # Aligns by index, not position
1784- print (df)
1785+ df
17851786
17861787 # Series with partial index match
17871788 s2 = pd.Series([100 , 200 ], index = [' x' , ' z' ])
17881789 df[' partial' ] = s2 # Missing 'y' gets NaN
1789- print (df)
1790+ df
17901791
17911792 # Series with non-matching indices
17921793 s3 = pd.Series([1000 , 2000 ], index = [' a' , ' b' ])
17931794 df[' nomatch' ] = s3 # All values become NaN
1794- print (df)
1795+ df
17951796
1797+ Avoiding Confusion:
1798+ ~~~~~~~~~~~~~~~~~~~
1799+
1800+ If you want positional assignment instead of index alignment:
1801+
1802+ .. ipython :: python
17961803
1797- # Avoiding Confusion:
1798- # If you want positional assignment instead of index alignment:
1799- # reset the Series index to match DataFrame index
1800- df[' s1_values' ] = s1.reindex(df.index)
1804+ # Use .values or .to_numpy() to assign by position
1805+ df[' position_based' ] = s1.values[:len (df)]
1806+ df
1807+
1808+ # Or align the Series to the DataFrame's index first
1809+ df[' reindexed' ] = s1.reindex(df.index)
1810+ df
0 commit comments