将数据帧列从字符串列表转换为元组

时间:2017-09-20 17:27:52

标签: python pandas dataframe tuples

我在列表中有网址。这是数据帧的一个元素。我需要将这些字符串列表中的每一个转换为像元组一样的可哈希类型。我用逗号读了那个元组(a,),在转换时保留了列表中的字符串。在应用于整列数据框时,我似乎无法使其工作。可能缺少一些简单的东西

df['url'] = tuple(df['url',]) ...无效

flatframe['url'] = flatframe['url'].apply(tuple) ...有效,但不保留字符串

这里有几行数据:

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

1 个答案:

答案 0 :(得分:0)

让我们说你的数据框是这样的:

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"])

然后你可以试试:

df.artisturl = df.artisturl.apply(lambda x: tuple(x) if type(x)!= str else tuple([x]))

这将仅对非字符串的条目应用元组,并转换为列表,然后转换为字符串条目。好像它是一个字符串并且你应用元组它会给每个字符的元组作为条目。

您的专栏artisturl将显示为:

>>> 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