![](/img/trans.png)
[英]Python Pandas Dataframe: Using Values in Column to Create New Columns
[英]pandas dataframe create new columns and fill values by using the values of the first column
我有一個熊貓數據框df
,它只有一列col
。 我想循環col
值,並通過使用第一列col
的值添加列以填充值。 例如,第一行是一個列表,其中包含3個元素['text1','text2','text3']
。 我想添加3列,並使用'text1'
, 'text2'
和'text3'
填充值。
import pandas as pd
df=pd.DataFrame({'col':[['text1','text2','text3'],['mext1','mext2'],['cext1']]})
df
col
0 [text1, text2, text3]
1 [mext1, mext2]
2 [cext1]
我想要這樣:
col col_1 col_2 col_3
0 [text1, text2, text3] text1 text2 text3
1 [mext1, mext2] mext1 mext2 Nan
2 [cext1] cext1 Nan Nan
您的幫助將不勝感激。
使用DataFrame
構造函數的另一種解決方案,需要rename
列和add_prefix
:
print (pd.DataFrame(df.col.values.tolist(), index=df.col)
.rename(columns = lambda x: x+1)
.add_prefix('col_')
.reset_index())
col col_1 col_2 col_3
0 [text1, text2, text3] text1 text2 text3
1 [mext1, mext2] mext1 mext2 None
2 [cext1] cext1 None None
解決方案,其中通過str.len
在col
列中找到列表的max
長度:
cols = df.col.str.len().max() + 1
print (cols)
4
print (pd.DataFrame(df.col.values.tolist(), index=df.col,columns = np.arange(1, cols))
.add_prefix('col_')
.reset_index())
col col_1 col_2 col_3
0 [text1, text2, text3] text1 text2 text3
1 [mext1, mext2] mext1 mext2 None
2 [cext1] cext1 None None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.