@@ -1751,30 +1751,40 @@ Key Points:
1751
1751
* This behavior is consistent across df[col] = series and df.loc[:, col] = series
1752
1752
1753
1753
Examples:
1754
- .. ipython :: python
1754
+ ~~~~~~~~~
1755
1755
1756
- import pandas as pd
1756
+ .. ipython :: python
1757
1757
1758
1758
# Create a DataFrame
1759
1759
df = pd.DataFrame({' values' : [1 , 2 , 3 ]}, index = [' x' , ' y' , ' z' ])
1760
+ df
1760
1761
1761
1762
# Series with matching indices (different order)
1762
1763
s1 = pd.Series([10 , 20 , 30 ], index = [' z' , ' x' , ' y' ])
1763
1764
df[' aligned' ] = s1 # Aligns by index, not position
1764
- print (df)
1765
+ df
1765
1766
1766
1767
# Series with partial index match
1767
1768
s2 = pd.Series([100 , 200 ], index = [' x' , ' z' ])
1768
1769
df[' partial' ] = s2 # Missing 'y' gets NaN
1769
- print (df)
1770
+ df
1770
1771
1771
1772
# Series with non-matching indices
1772
1773
s3 = pd.Series([1000 , 2000 ], index = [' a' , ' b' ])
1773
1774
df[' nomatch' ] = s3 # All values become NaN
1774
- print (df)
1775
+ df
1775
1776
1777
+ Avoiding Confusion:
1778
+ ~~~~~~~~~~~~~~~~~~~
1776
1779
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