I have urls in a list. This is an element of a dataframe. I need convert each of these lists of strings to a hashable type like tuples. I've read that tuple(a,) with the comma, preserves the strings inside the lists when converting. I can't seem to get this to work when applying to a whole column of dataframe. prob missing something simple
df['url'] = tuple(df['url',])
...doesn't work
flatframe['url'] = flatframe['url'].apply(tuple)
...works but doesn't preserve strings
here are a couple of rows of data:
index artist ranking song songurl songtext artisturl year
2280 (Lady Antebellum,) 81 [Bartender (Lady Antebellum song)] [/wiki/Bartender_(Lady_Antebellum_song)] "Bartender (Lady Antebellum song)" /wiki/Lady_Antebellum 2014
2281 (Naughty Boy, Sam Smith) 82 [La La La (Naughty Boy song)] [/wiki/La_La_La_(Naughty_Boy_song)] "La La La (Naughty Boy song)" [/wiki/Naughty_Boy, /wiki/Sam_Smith_(singer)] 2014
2282 (Robin Thicke, T.I., Pharrell Williams) 83 [Blurred Lines] [/wiki/Blurred_Lines] "Blurred Lines" [/wiki/Robin_Thicke, /wiki/T.I., /wiki/Pharrel... 2014
2283 (Lady Gaga, R. Kelly) 84 [Do What U Want] [/wiki/Do_What_U_Want] "Do What U Want" [/wiki/Lady_Gaga, /wiki/R._Kelly] 2014
Lets say your dataframe is something like this:
import pandas as pd
pd.set_printoptions(max_columns=10)
df = pd.DataFrame(
[[2280, ("Lady Antebellum"), 81, ["Bartender (Lady Antebellum song)"], ["/wiki/Bartender_(Lady_Antebellum_song)"], "Bartender (Lady Antebellum song)", "/wiki/Lady_Antebellum", 2014],
[2281, "(Naughty Boy, Sam Smith)", 82, ["La La La (Naughty Boy song)"], ["/wiki/La_La_La_(Naughty_Boy_song)"], "La La La (Naughty Boy song)", ["/wiki/Naughty_Boy", "/wiki/Sam_Smith_(singer)"], 2014],
[2282, "(Robin Thicke, T.I., Pharrell Williams)", 83, ["Blurred Lines"], ["/wiki/Blurred_Lines"], "Blurred Lines", ["/wiki/Robin_Thicke", "/wiki/T.I. /wiki/Pharrel"], 2014],
[2283, "(Lady Gaga, R. Kelly)", 84, ["Do What U Want"], ["/wiki/Do_What_U_Want"], "Do What U Want", ["/wiki/Lady_Gaga", "/wiki/R._Kelly"], 2014]],
columns = ["index", "artist", "ranking", "song", "songurl", "songtext", "artisturl", "year"])
Then you can try with:
df.artisturl = df.artisturl.apply(lambda x: tuple(x) if type(x)!= str else tuple([x]))
This will apply tuple only to entries that are not strings, and convert to list and then to tuple entries that are strings. As if it is a string and you apply tuple it will give a tuple with each character as entries.
Your column artisturl
would then look as:
>>> df.artisturl
0 ('/wiki/Lady_Antebellum',)
1 ('/wiki/Naughty_Boy', '/wiki/Sam_Smith_(singer)')
2 ('/wiki/Robin_Thicke', '/wiki/T.I. /wiki/Pharr...
3 ('/wiki/Lady_Gaga', '/wiki/R._Kelly')
Name: artisturl
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.