[英]Split column with separator
| A | B
| a;b;c | 1;2;3
| a;b;c;d | 1
為了拆分列,我正在使用
new = df["A"].str.split(";", n=5, expand=True).
df['A1'] = new[0]
df['A2'] = new[1]
df['A3'] = new[2]
df['A4'] = new[3]
df.drop(columns=["A"], inplace=True)
df['B1'] = new[0]
df['B2'] = new[1]
df['B3'] = new[2]
df.drop(columns=["B"], inplace=True)
有沒有其他替代方法,我不需要計算每列中的數據數量? 我仍然需要 output 類似於:
| A1| A2| A3| A4| B1| B2| B3
| a | b | c | | 1 | 2 | 3
| a | b | c | d | 1 | |
謝謝!
無需指定拆分數量,因為默認情況下會在分隔符的每個實例上拆分。 結果將是 DataFrame,其中列是 RangeIndex,因此添加列作為前綴。 循環遍歷每個系列(因為它是concat
),然后連接以加入結果。
df = pd.concat([df[col].str.split(';', expand=True).add_prefix(col) for col in df.columns],
axis=1)
A0 A1 A2 A3 B0 B1 B2
0 a b c None 1 2 3
1 a b c d 1 None None
請注意, 'B'
列包含字符串'1'
,因此如果您想要使用數字pd.to_numeric
:
numerics = df.columns[df.columns.str.startswith('B')]
df[numerics] = df[numerics].apply(pd.to_numeric, errors='coerce')
A0 A1 A2 A3 B0 B1 B2
0 a b c None 1 2.0 3.0
1 a b c d 1 NaN NaN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.