I have a problem. Im a begginer and Im trying to take the second part of the 'Nation' column who is written like this: 'us US' and I want to take the second part (US)
df['Nation'] = df.Nation.apply(lambda pos: pos.split("")[0])
I try it but this takes the first part (us)
CodePudding user response:
[0]
means the first part. Changing it to [1]
or [-1]
would solve the issue, but there is a better way: use .str
methods
df['Nation'] = df.Nation.str.split().str[1]
CodePudding user response:
Probably your column Nation
are mixed with some data not of string type. In such case, cast your column to string first by .astype()
before splitting string by .str.split()
, as follows:
df['Nation'] = df['Nation'].astype(str).str.split().str[1]
or use .astype()
with str.rsplit()
, as follows:
df['Nation'] = df['Nation'].astype(str).str.rsplit().str[-1]