提取逗号分隔值以创建新列
Extracting comma separeted values to make new columns
我有一个只有一列的 df。 dtype 是 object
:
column_1
1,2,3
2,3,4
我想提取那些comman分隔值来创建新的列,像这样:
column_1 column_2 column_3 column_4
1,2,0.3 1 2 0.3
2,3,0.4 2 3 0.4
我尝试了一些 .split(',')
但失败了。
最好的方法是什么?
谢谢
试试 split
out = df.join(pd.DataFrame(df.column_1.str.split(',').tolist(),index=df.index))
Out[275]:
column_1 0 1 2
0 1,2,3 1 2 3
1 2,3,4 2 3 4
使用 split 和 expand=True 选项
txt="""
column_1
1,2,3
2,3,4
"""
df=pd.read_csv(io.StringIO(txt),sep='\n')
df[['column_2','column_3','column_4']]=df['column_1'].str.split(',',expand=True)
print(df)
输出:
column_1 column_2 column_3 column_4
0 1,2,3 1 2 3
1 2,3,4 2 3 4
我会这样做:
df[["Column_%d"%i for i in range(2,5)]] = df['column_1'].str.split(',', expand=True)
我有一个只有一列的 df。 dtype 是 object
:
column_1
1,2,3
2,3,4
我想提取那些comman分隔值来创建新的列,像这样:
column_1 column_2 column_3 column_4
1,2,0.3 1 2 0.3
2,3,0.4 2 3 0.4
我尝试了一些 .split(',')
但失败了。
最好的方法是什么?
谢谢
试试 split
out = df.join(pd.DataFrame(df.column_1.str.split(',').tolist(),index=df.index))
Out[275]:
column_1 0 1 2
0 1,2,3 1 2 3
1 2,3,4 2 3 4
使用 split 和 expand=True 选项
txt="""
column_1
1,2,3
2,3,4
"""
df=pd.read_csv(io.StringIO(txt),sep='\n')
df[['column_2','column_3','column_4']]=df['column_1'].str.split(',',expand=True)
print(df)
输出:
column_1 column_2 column_3 column_4
0 1,2,3 1 2 3
1 2,3,4 2 3 4
我会这样做:
df[["Column_%d"%i for i in range(2,5)]] = df['column_1'].str.split(',', expand=True)