我需要将我的列表转换为一列pandas dataframe
当前列表(len = 3):
['Thanks You',
'Its fine no problem',
'Are you sure']
必需的Pandas DF(shape = 3,):
0 Thank You
1 Its fine no problem
2 Are you sure
请注意,这些数字代表上面所需的Pandas DF中的索引。
答案 0 :(得分:100)
使用:
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
谢谢DYZ:
#default column name 0
df = pd.DataFrame(L)
print (df)
0
0 Thanks You
1 Its fine no problem
2 Are you sure
答案 1 :(得分:4)
如果您的列表如下所示:[1,2,3],您可以这样做:
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
df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']
df
得到这个:
col1
0 1
1 2
2 3
答案 2 :(得分:3)
您可以直接致电
方法并将您的列表作为参数传递。
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
答案 3 :(得分:2)
示例:
['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
希望这会有所帮助!
答案 4 :(得分:0)
要将列表转换为Pandas Core数据框架,我们需要使用 pandas 软件包中的 DataFrame 方法。
执行上述操作的方法有多种。
将熊猫作为pd导入
数据= pd.DataFrame(列数据)
Data.columns = ['Column_Name']
因此,对于上述问题,代码段为
import pandas as pd
Content = ['Thanks You',
'Its fine no problem',
'Are you sure']
Data = pd.DataFrame({'Text': Content})