【问题标题】:How to text to columns in pandas and create new columns?如何在 Pandas 中向列发送文本并创建新列?
【发布时间】:2022-01-22 00:04:23
【问题描述】:

我有一个如下所示的 csv 文件,名称列的名称用逗号分隔,我想将它们用逗号分隔并将它们附加到新列并创建相同的 csv,类似于 excel 中列的文本,问题是某些行有随机数量的名称。

| Address | Name               |
| 1st st  | John, Smith        |
|2nd st.  | Andrew, Jane, Aaron|

我的熊猫代码看起来像这样

df1 = pd.read_csv('sample.csv')
df1['Name'] = df1['Name'].str.split(',', expand=True)
df1.to_csv('results.csv',index=None)

当然这不起作用,因为列的长度必须与键的长度相同。预期的输出是

| Address | Name  |     |      |
| 1st st  | John  |Smith|      |
|2nd st.  | Andrew| Jane| Aaron|

【问题讨论】:

  • 是连续2个逗号的最大值吗?如果那么您可以根据 , -> df1[['Name1','Name2','Name3']] = df1.Name.str.split(',' ,expand =True) 然后 df1.drop('Name',axis=1,inplace = True) 拆分为 3 列
  • 某些行中的最大名称几乎是 15 个,但可能会有所不同,问题是我想让它足够通用以至于它不重要。我不想硬编码列名

标签: python pandas


【解决方案1】:

计算逗号的最大数量,然后相应地分配给新列。

max_commas = df['name'].str.split(',').transform(len).max()
df[[f'name_{x}' for x in range(max_commas)]] = df['name'].str.split(',', expand=True)

输入df:

      col                        name
0  1st st                 john, smith
1  2nd st          andrew, jane, aron
2  3rd st  harry, philip, anna, james

输出:

      col                        name  name_0  name_1 name_2 name_3
0  1st st                 john, smith    john   smith   None   None
1  2nd st          andrew, jane, aron  andrew    jane   aron   None
2  3rd st  harry, philip, anna, james   harry  philip   anna  james

【讨论】:

  • 这看起来是一个很好的解决方案,这也是我刚刚尝试和工作的。 df1.join(df1['name'].str.split(',',expand=True)).to_csv('results.csv',index=None)
  • 我认为你的解决方案比我的好。我必须通过首先将结果列表转换为它们的长度来查找最大逗号数。在您刚刚加入的解决方案中。
【解决方案2】:

你可以的

out = df.join(df['Name'].str.split(', ',expand=True).add_prefix('name_'))

【讨论】:

    猜你喜欢
    • 2021-01-21
    • 2021-09-11
    • 2021-10-09
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多