我有一個像波紋管一樣的 CSV 資料集
f1 f2 f3 ... label1 label2
float float float ... 00010 00001
... 01000 00010
每個標簽列都是二進制格式。我想在保留標題的情況下將一列更改為多列。每個零和一應該分開放置在不同的列中,如下所示
f1 f2 f3 ... label1 label2
float float float ... 0,0,0,1,0 0,0,0,0,1
... 0,1,0,0,0 0,0,0,1,0
你能指導我如何在 Python 中做到這一點嗎?謝謝。
uj5u.com熱心網友回復:
您可以使用以下方法非常有效地執行此操作pandas dataframe:(注意:還有其他方法,例如讀取 csv 并編輯每一行)。
import pandas as pd
# some test data using strings for their binary equivalents.
example_data = {'f':['a', 'b', 'c'], 'binary_data':['111','101','001']}
df = pd.DataFrame(example_data)
print(df)
def split_parts(row):
return [x for x in row['binary_data']]
df['split_data']=df.apply(split_parts, axis=1)
print(df)
print(type(df['split_data']))
這是“樣本”輸入:
f binarydata
0 a 111
1 b 101
2 c 100
這是結果:
f binary_data split_data
0 a 111 [1, 1, 1]
1 b 101 [1, 0, 1]
2 c 001 [0, 0, 1]
上面的列split_data是一個字串串列,每個值代表二進制資料的每個部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441862.html
