【问题标题】:Dataframe column to list of strings (with groupby)数据框列到字符串列表(使用 groupby)
【发布时间】:2019-09-26 21:21:34
【问题描述】:

我有一个数据框,我想将其中的一列作为字符串列表获取,以便从以下内容中获取:

df = pd.DataFrame({'customer':['a','a','a','b','b'],
         'location':['1','2','3','4','5']})

我可以得到如下数据框:

a  ['1','2','3']
b  ['4','5']

其中一列是客户,另一列是他们所在位置的字符串列表。

我已经尝试过 df.astype(str).values.tolist() 但我似乎无法通过 groupby 来获取每个客户的列表。

【问题讨论】:

  • df.groupby('customer')['location'].apply(list)?
  • 这样,但我不能这样做,因为那时我没有字符串列表

标签: python-3.x string pandas list


【解决方案1】:

随便用

df.groupby('customer').location.unique()
Out[58]: 
customer
a    [1, 2, 3]
b       [4, 5]
Name: location, dtype: object

这是string类型,只是没有显示引用

df.groupby('customer').location.unique()[0][0]
Out[61]: '1'

您还应该知道列表中的字符串输入不会在熊猫对象中显示引号

pd.Series([['1','2']])
Out[64]: 
0    [1, 2]
dtype: object

【讨论】:

    猜你喜欢
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    相关资源
    最近更新 更多