@@ -1771,30 +1771,40 @@ Key Points:
1771
1771
* This behavior is consistent across df[col] = series and df.loc[:, col] = series
1772
1772
1773
1773
Examples:
1774
- .. ipython :: python
1774
+ ~~~~~~~~~
1775
1775
1776
- import pandas as pd
1776
+ .. ipython :: python
1777
1777
1778
1778
# Create a DataFrame
1779
1779
df = pd.DataFrame({' values' : [1 , 2 , 3 ]}, index = [' x' , ' y' , ' z' ])
1780
+ df
1780
1781
1781
1782
# Series with matching indices (different order)
1782
1783
s1 = pd.Series([10 , 20 , 30 ], index = [' z' , ' x' , ' y' ])
1783
1784
df[' aligned' ] = s1 # Aligns by index, not position
1784
- print (df)
1785
+ df
1785
1786
1786
1787
# Series with partial index match
1787
1788
s2 = pd.Series([100 , 200 ], index = [' x' , ' z' ])
1788
1789
df[' partial' ] = s2 # Missing 'y' gets NaN
1789
- print (df)
1790
+ df
1790
1791
1791
1792
# Series with non-matching indices
1792
1793
s3 = pd.Series([1000 , 2000 ], index = [' a' , ' b' ])
1793
1794
df[' nomatch' ] = s3 # All values become NaN
1794
- print (df)
1795
+ df
1795
1796
1797
+ Avoiding Confusion:
1798
+ ~~~~~~~~~~~~~~~~~~~
1799
+
1800
+ If you want positional assignment instead of index alignment:
1801
+
1802
+ .. ipython :: python
1796
1803
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