将列表转换为熊猫数据框列

我需要将我的列表转换成一列熊猫数据框架。

最新名单(len = 3) :

['Thanks You',
'Its fine no problem',
'Are you sure']

需要的大熊猫 DF (形状 = 3,) :

0 Thank You
1 Its fine no problem
2 Are you sure

N.B. The numbers represent index in the required Pandas DF above.

440185 次浏览

用途:

L = ['Thanks You', 'Its fine no problem', 'Are you sure']


#create new df
df = pd.DataFrame({'col':L})
print (df)


col
0           Thanks You
1  Its fine no problem
2         Are you sure

df = pd.DataFrame({'oldcol':[1,2,3]})


#add column to existing df
df['col'] = L
print (df)
oldcol                  col
0       1           Thanks You
1       2  Its fine no problem
2       3         Are you sure

谢谢:

#default column name 0
df = pd.DataFrame(L)
print (df)
0
0           Thanks You
1  Its fine no problem
2         Are you sure

如果你的清单看起来像这样: [1,2,3]你可以做:

import pandas as pd


lst = [1,2,3]
df = pd.DataFrame([lst])
df.columns =['col1','col2','col3']
df

得到这个:

    col1    col2    col3
0   1       2       3

或者,您也可以创建如下列表:

import numpy as np
import pandas as pd


df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']
df

得到这个:

  col1
0   1
1   2
2   3

例如:

['Thanks You',
'Its fine no problem',
'Are you sure']

代码块:

import pandas as pd
df = pd.DataFrame(lst)

产出:

    0
0   Thanks You
1   Its fine no problem
2   Are you sure

不建议删除熊猫数据框的列名。但是,如果你仍然希望你的数据帧没有头(按照你在问题中发布的格式) ,你可以这样做:

df = pd.DataFrame(lst)
df.columns = ['']

产出将是这样的:

0   Thanks You
1   Its fine no problem
2   Are you sure

或者

df = pd.DataFrame(lst).to_string(header=False)

但是输出将是一个列表,而不是一个数据框架:

0           Thanks You
1  Its fine no problem
2         Are you sure

希望这个能帮上忙!

您可以直接调用 pd.DataFrame()方法并将列表作为参数传递。

import pandas as pd
l = ['Thanks You','Its fine no problem','Are you sure']
pd.DataFrame(l)

产出:

                      0
0            Thanks You
1   Its fine no problem
2          Are you sure

如果你有多个列表,并且你想把它做成一个数据框架。你可以这样做:

import pandas as pd
names =["A","B","C","D"]
salary =[50000,90000,41000,62000]
age = [24,24,23,25]
data = pd.DataFrame([names,salary,age]) #Each list would be added as a row
data = data.transpose() #To Transpose and make each rows as columns
data.columns=['Names','Salary','Age'] #Rename the columns
data.head()

产出:

    Names   Salary  Age
0       A    50000   24
1       B    90000   24
2       C    41000   23
3       D    62000   25

为了将一个列表转换成熊猫核心数据框架,我们需要使用 熊猫包中的 数据框架方法。

执行上述操作有不同的方法(假设熊猫是以 pd的形式进口的)

  1. pandas.DataFrame({'Column_Name':Column_Data})
  • Column _ Name : String
  • Column _ Data : List Form
  1.  Data = pandas.DataFrame(Column_Data)`
    Data.columns = ['Column_Name']
    

因此,对于上面提到的问题,代码片段是

import pandas as pd


Content = ['Thanks You',
'Its fine no problem',
'Are you sure']


Data = pd.DataFrame({'Text': Content})

您也可以 assign()一个列表到一个现有的数据框架。如果您正在链接多个方法,并且需要分配一个需要稍后在链中使用的列,那么这一点特别有用。

df = pd.DataFrame()
df1 = df.assign(col=['Thanks You', 'Its fine no problem', 'Are you sure'])

res