簡體   English   中英

如何填充(基於數據框的索引)空列

[英]How to fill (based on the index of a dataframe) an empty column

我正在嘗試將“信息”列添加到我的數據框(df3)並用字符串值填充它(如果索引為 0,則為“True”,否則為“False”)。 問題是熊貓在每一行中都放置了'False' ,即使在索引為 0 的行中也是如此(參見下面的輸出)。

輸入 :

import pandas as pd
import numpy as np

df1 = pd.DataFrame({'Column1': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
                    'Column2': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                    'Column3': ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'],
                    'Column4': ['K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'],
                    'Column5': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
                    'Column6': ['XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI', 'XVII', 'XVIII', 'XIX', 'XX'],
                    'Column7': ['U', 'V', 'W', 'X', 'Y', 'Z', '', '', '', ''],
                    'Column8': [21, 22, 23, 24, 25, 26, pd.NA, pd.NA, pd.NA, pd.NA],
                    'Column9': ['XXI', 'XXII', 'XXIII', 'XXIV', 'XXV', 'XXVI', '', '', '', '']})

column_names = ['Letters', 'Numbers', 'RomanNumerals']
df3 = pd.DataFrame(columns = column_names)

i=0
while i<len(df1.columns):
    df2 = df1.iloc[:, i:i+3]
    df2.columns = column_names
    df3 = pd.concat([df3, df2])
    i+=3

df3.dropna(inplace=True)

for index, row in df3.iterrows():
    df3['Information'] = np.where(index == 0, True,  False)

display(df3)

輸出 :

信件 數字 羅馬數字 信息
0 一個 1 錯誤的
1 2 錯誤的
2 C 3 錯誤的
3 D 4 錯誤的
4 5 錯誤的
5 F 6 錯誤的
6 G 7 錯誤的
7 H 8 錯誤的
8 9 錯誤的
9 Ĵ 10 X 錯誤的
0 ķ 11 十一 錯誤的
1 大號 12 第十二 錯誤的
2 13 十三 錯誤的
3 ñ 14 第十四 錯誤的
4 15 第十五 錯誤的
5 16 第十六 錯誤的
6 17 第十七 錯誤的
7 R 18 第十八 錯誤的
8 小號 19 第十九 錯誤的
9 20 XX 錯誤的
0 ü 21 二十一 錯誤的
1 22 二十二 錯誤的
2 W 23 二十三 錯誤的
3 X 24 二十四 錯誤的
4 25 二十五 錯誤的
5 Z 26 二十六 錯誤的

這種情況有解釋嗎?

使用此代碼段更改 for 循環


df3['Information']= df3.index.map(lambda x: x==0)

在 for 循環中發生的是您實際上基於標量創建了一個新列。 不是你輸入的


df3['Information'] = np.where(index == 0, True,  False)

代替


row['Information'] = np.where(index == 0, True,  False)

但是即使上面的代碼也不起作用,因為您什么都不分配

編輯:

另一種方法(為了進一步解釋,您可以檢查pandas dataframe apply


def get_information(index):
    if index==0:
        return True
    else:
        return False

df3['Information']= df3.index.map(get_information)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM