Замените значения ячеек в каждой строке столбца панд, используя для бинаризатора и для цикла - PullRequest
0 голосов
/ 06 ноября 2018

Мне нужна помощь здесь. Я пытаюсь изменить один столбец в моем файле .csv, некоторые из которых пусты, а некоторые со списком категорий. Как следует:

tdaa_matParent,tdaa_matParentQty
[],[]
[],[]
[],[]
[BCA_Aluminum],[1.3458]
[BCA_Aluminum],[1.3458]
[BCA_Aluminum],[1.3458]
[BCA_Aluminum],[1.3458]
[],[]
[Dye Penetrant Solution, BCA_Aluminum],[0.002118882, 1.3458]

Но до сих пор мне удалось только преобразовать в двоичную форму первый столбец (tdaa_matParent), но я не смог заменить 1-е на соответствующее им значение количества, как это.

s = materials['tdaa_matParent']
mlb = MultiLabelBinarizer()
df = pd.DataFrame(mlb.fit_transform(s),columns=mlb.classes_)

BCA_Aluminum,Dye Penetrant Solution,tdaa_matParentQty
0,0,[]
0,0,[]
0,0,[]
1,0,[1.3458,0]
1,0,[1.3458,0]
1,0,[1.3458,0]
1,0,[1.3458,0]
0,0,[]
1,1,[1.3458,0.002118882]

Но что я действительно хочу, так это новый набор столбцов для каждой категории столбцов (то есть BCA_Aluminium и Dye Penetrant Solution). Также каждый столбец, если он заполнен, должен быть заменен значением второго столбца (tdaa_matParentQty).

Например:

BCA_Aluminum,Dye Penetrant Solution
0,0
0,0
0,0
1.3458,0
1.3458,0
1.3458,0
1.3458,0
0,0
1.3458,0.002118882

Ответы [ 2 ]

0 голосов
/ 07 ноября 2018

Спасибо! Я построил другой подход, который также работает (хотя и немного медленнее). Любые предложения, не стесняйтесь поделиться:)

df_matParent_with_Qty = pd.DataFrame()

# For each row in the dataframe (index and row´s column info),
for index, row in ass_materials.iterrows():

# For each row iteration save name of the element (matParent) and it´s index number:   
    for i, element in enumerate(row["tdaa_matParent"]):
#         print(i)
#         print(element)
# Fill in the empty dataframe with lists from each element
# And in each of their corresponding index (row), replace it with the value index inside the matParentqty list.
        df_matParent_with_Qty.loc[index,element] = row['tdaa_matParentQty'][i]

df_matParent_with_Qty.head(10)
0 голосов
/ 06 ноября 2018

Вот как я это сделал бы с помощью встроенных средств Python для примеров данных, представленных в вопросе:

from collections import OrderedDict
import pandas as pd

# simple case - material names are known before we process the data - allows to solve the problem with a single for loop
# OrderedDict is used to preserve the order of material names during the processing
base_result = OrderedDict([
    ('BCA_Aluminum', .0),
    ('Dye Penetrant Solution', .0)])
result = list()

with open('1.txt', mode='r', encoding='UTF-8') as file:

    # skip header
    file.readline()

    for line in file:

        # copy base_result to reuse it during the looping
        base_result_copy = base_result.copy()

        # modify base result only if there are values in the current line
        if line != '[],[]\n':
            names, values = line.strip('[]\n').split('],[')
            for name, value in zip(names.split(', '), values.split(', ')):
                base_result_copy[name] = float(value)

        # append new line (base or modified) to the result
        result.append(base_result_copy.values())

# turn list of lists into pandas dataframe
result = pd.DataFrame(result, columns=base_result.keys())
print(result)

Выход:

   BCA_Aluminum  Dye Penetrant Solution
0        0.0000                0.000000
1        0.0000                0.000000
2        0.0000                0.000000
3        1.3458                0.000000
4        1.3458                0.000000
5        1.3458                0.000000
6        1.3458                0.000000
7        0.0000                0.000000
8        1.3458                0.002119

0.002119 вместо 0.002118882 из-за того, что pandas отображает поплавки по умолчанию, исходная точность сохраняется в реальных данных в кадре данных.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...