@@ -1751,30 +1751,40 @@ Key Points:
17511751* This behavior is consistent across df[col] = series and df.loc[:, col] = series
17521752
17531753Examples:
1754- .. ipython :: python
1754+ ~~~~~~~~~
17551755
1756- import pandas as pd
1756+ .. ipython :: python
17571757
17581758 # Create a DataFrame
17591759 df = pd.DataFrame({' values' : [1 , 2 , 3 ]}, index = [' x' , ' y' , ' z' ])
1760+ df
17601761
17611762 # Series with matching indices (different order)
17621763 s1 = pd.Series([10 , 20 , 30 ], index = [' z' , ' x' , ' y' ])
17631764 df[' aligned' ] = s1 # Aligns by index, not position
1764- print (df)
1765+ df
17651766
17661767 # Series with partial index match
17671768 s2 = pd.Series([100 , 200 ], index = [' x' , ' z' ])
17681769 df[' partial' ] = s2 # Missing 'y' gets NaN
1769- print (df)
1770+ df
17701771
17711772 # Series with non-matching indices
17721773 s3 = pd.Series([1000 , 2000 ], index = [' a' , ' b' ])
17731774 df[' nomatch' ] = s3 # All values become NaN
1774- print (df)
1775+ df
17751776
1777+ Avoiding Confusion:
1778+ ~~~~~~~~~~~~~~~~~~~
17761779
1777- # Avoiding Confusion:
1778- # If you want positional assignment instead of index alignment:
1779- # reset the Series index to match DataFrame index
1780- df[' s1_values' ] = s1.reindex(df.index)
1780+ If you want positional assignment instead of index alignment:
1781+
1782+ .. ipython :: python
1783+
1784+ # Use .values or .to_numpy() to assign by position
1785+ df[' position_based' ] = s1.values[:len (df)]
1786+ df
1787+
1788+ # Or align the Series to the DataFrame's index first
1789+ df[' reindexed' ] = s1.reindex(df.index)
1790+ df
0 commit comments