So I was just answering a question and I came across something interesting:
The dataframe looks like this:
string1 string2
0 abc def
1 ghi jkl
2 mno pqr
3 stu vwx
So when I do the following, the assigning of new columns works:
df['string3'] = df.string2
print(df)
string1 string2 string3
0 abc def def
1 ghi jkl jkl
2 mno pqr pqr
3 stu vwx vwx
But when I use pandas.DataFrame.Series.sample, the new column does net get assigned, at least not the sampled one:
df['string4'] = df.string2.sample(len(df.string2))
print(df)
string1 string2 string3 string4
0 abc def def def
1 ghi jkl jkl jkl
2 mno pqr pqr pqr
3 stu vwx vwx vwx
So I tested some things:
Test1 Using sample without assign, gives us correct output:
df.string2.sample(len(df.string2))
2 pqr
1 jkl
0 def
3 vwx
Name: string2, dtype: object
Test2 Cannot overwrite either:
df['string2'] = df.string2.sample(len(df.string2))
print(df)
string1 string2
0 abc def
1 ghi jkl
2 mno pqr
3 stu vwx
This works but why?
df['string2'] = df.string2.sample(len(df.string2)).values
print(df)
string1 string2
0 abc jkl
1 ghi def
2 mno vwx
3 stu pqr
Why do I need to explicitly use .values or .tolist() to get the assigning correct?
intrinsic data alignment. Thank you for the infomation. @ScottBoston - Erfan