【问题标题】:Split list of text in pandas dataframe拆分熊猫数据框中的文本列表
【发布时间】:2019-05-12 09:49:47
【问题描述】:

我的 pandas 数据框由文本列表组成,我想将文本拆分为 ,

df['c1']=['this is text one','this is text two','this is text three']

我试过了

new = df["c1"].str.split(",", n = 1, expand = True)

但我是 Nan 在新变量上

预期输出

c1='this is text one'
c1='this is text two'
c1='this is text three'

只要拆分列表中的文本,其他输出就可以了。感谢您的帮助 完整代码

import pandas as pd
data={"C1":[["this is text one","this is text two","this is text three"]]}
df=pd.DataFrame(data)
df.head()

【问题讨论】:

  • 我能看到完整的代码吗?
  • 我无法分享完整的代码,但流程看起来像这样 ``` import pandas as pd data={"C1":[["this is text one","this is text two ","这是文本三"]]} df=pd.DataFrame(data) print(df.head()) ```
  • 我想知道df数组的结构

标签: python string pandas list python-3.6


【解决方案1】:

您不需要 pandas 来拆分可以用于循环的数组

这就是你需要的


for i in df['C1']:
    for each in i:
        print(each) #outputs each element in the array

【讨论】:

    【解决方案2】:

    使用np.concatenate() 并调用数据框构造函数(因为您已经有了一个字符串列表):

    df_new=pd.DataFrame(np.concatenate(df1.C1),columns=['C1'])
    #or pd.DataFrame(df1.C1.values.tolist()).T
    

                       C1
    0    this is text one
    1    this is text two
    2  this is text three
    

    【讨论】:

      【解决方案3】:

      您的问题有点令人困惑-您说您已经有一个文本列表,那么为什么要拆分它?如果你的意思是你有一个数据框,其中的字符串必须用逗号分隔,你可以这样做。

      import pandas as pd
      
      df = pd.DataFrame()
      
      df['c1']=['this is the first text, which has some commas, in it',
                'this is text two, which also has commas']
      
      df['lists'] = df['c1'].apply(lambda txt: txt.split(','))
      
      df.head()
      

      运行df['lists'][0] 然后给出['this is the first text', ' which has some commas', ' in it']

      【讨论】:

      • 这段代码给我一个错误。 AttributeError: 'list' 对象没有属性 'split'
      • 如果你运行两段代码就不会。如果您将第二部分运行两次,或者将第二部分与您发布的位一起使用。
      • 好的,我明白你的意思,但在我的问题中,df['c1'] 由列表组成,而不仅仅是列表。谢谢
      • 好吧 - 但是你在看什么?如果它已经是列表列表,为什么要拆分它?您想要列表列表的列表吗?
      猜你喜欢
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 2018-07-26
      • 2016-11-16
      • 2013-06-23
      • 2019-10-26
      相关资源
      最近更新 更多