programing

Panda 데이터 프레임에서 열 수를 검색하려면 어떻게 해야 합니까?

minecode 2022. 12. 10. 10:57
반응형

Panda 데이터 프레임에서 열 수를 검색하려면 어떻게 해야 합니까?

판다 데이터 프레임의 열 수를 프로그래밍 방식으로 검색하려면 어떻게 해야 합니까?나는 다음과 같은 것을 바라고 있었다:

df.num_columns

다음과 같은 경우:

import pandas as pd
df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

len(df.columns)
3

다른 방법:

df.shape[1]

(df.shape[0]행의 수)입니다.

데이터 프레임을 유지하는 변수가 df라고 불리는 경우:

len(df.columns)

는 열의 수를 나타냅니다.

줄 수를 원하는 사용자:

len(df.index)

행과 열의 수가 모두 포함된 태플의 경우:

df.shape

아직 본 적이 없어서 놀랐어요. 더 이상 떠들지 말고, 여기 있어요.

df.tmp.size

df.info() 함수는 다음과 같은 결과를 제공합니다.sep 매개 변수 또는 sep을 사용하지 않고 Panda의 read_csv 메서드를 사용하는 경우 " ".

raw_data = pd.read_csv("a1:\aa2/aaa3/data.csv")
raw_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5144 entries, 0 to 5143
Columns: 145 entries, R_fighter to R_age

다음과 같은 열 번호 및 열 정보를 가져오는 여러 옵션이 있습니다.
확인해봅시다.

local_df = pd.DataFrame(np.random.randint(1,12,size=(2,6)),columns =['a'',b'',c'',d'',e'',f') 1.local_df.shape [ 1 ] -- > 쉐이프 Atribute return tuple as ( 행 & columns ) (0,1)

  1. local_df.info() --> info 메서드는 데이터 프레임에 대한 자세한 정보를 반환합니다.컬럼 수, 컬럼 유형, 늘 값 수가 아닌 값 수, 데이터 프레임별 메모리 사용량 등의 컬럼입니다.

  2. len(local_df.columns) --> columns 속성은 데이터 프레임 열의 인덱스 개체를 반환하고 len 함수는 사용 가능한 총 열을 반환합니다.

  3. 파라미터 0의 local_df.head(0) --> head 메서드는 실제로는 헤더 이외의 df의 첫 번째 행을 반환합니다.

열 수가 10개 이하라고 가정합니다.루프 재미: local_df의 x에 대해 li_count = 0: li_count = li_count + 1 인쇄(li_count)

총 모양에 행 색인 "컬럼"의 수를 포함하기 위해 개인적으로 열 수를 더합니다.df.columns.size속성과 함께pd.Index.nlevels/pd.MultiIndex.nlevels:

더미 데이터 설정

import pandas as pd

flat_index = pd.Index([0, 1, 2])
multi_index = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), names=["letter", "id"])

columns = ["cat", "dog", "fish"]

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_df = pd.DataFrame(data, index=flat_index, columns=columns)
multi_df = pd.DataFrame(data, index=multi_index, columns=columns)

# Show data
# -----------------
# 3 columns, 4 including the index
print(flat_df)
    cat  dog  fish
id                
0     1    2     3
1     4    5     6
2     7    8     9

# -----------------
# 3 columns, 5 including the index
print(multi_df)
           cat  dog  fish
letter id                
a      1     1    2     3
       2     4    5     6
b      1     7    8     9

프로세스 함수 작성:

def total_ncols(df, include_index=False):
    ncols = df.columns.size
    if include_index is True:
        ncols += df.index.nlevels
    return ncols

print("Ignore the index:")
print(total_ncols(flat_df), total_ncols(multi_df))

print("Include the index:")
print(total_ncols(flat_df, include_index=True), total_ncols(multi_df, include_index=True))

다음의 출력이 있습니다.

Ignore the index:
3 3

Include the index:
4 5

인덱스가 다음과 같은 경우 인덱스 수만 포함하려면pd.MultiIndex, 그 다음에, 당신은 그것을 던질 수 있습니다.isinstance정의된 함수를 체크인합니다.

다른 방법으로는df.reset_index().columns.size동일한 결과를 얻으려면 이 방법은 인덱스에 임시로 새 열을 삽입하고 열 수를 가져오기 전에 새 인덱스를 만들기 때문에 성능이 떨어집니다.

#use a regular expression to parse the column count
#https://docs.python.org/3/library/re.html

buffer = io.StringIO()
df.info(buf=buffer)
s = buffer.getvalue()
pat=re.search(r"total\s{1}[0-9]\s{1}column",s)
print(s)
phrase=pat.group(0)
value=re.findall(r'[0-9]+',phrase)[0]
print(int(value))
import pandas as pd
df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})


print(len(list(df.iterrows())))

행의 길이를 나타냅니다.

3

[Program finished]

이하에 나타냅니다.

  • pandas
    • Excel 진 :xlsxwriter

수를 가져오는 몇 가지 방법:

  • len(df.columns)->28
    • 여기에 이미지 설명 입력
  • df.shape[1]->28
    • ★★★★★★★★★★★★★★★★*df.shape = (592, 28)
    • 관련된
      • 수: " " ":df.shape[0]->592
  • df.columns.shape[0]->28
    • ★★★★★★★★★★★★★★★★*df.columns.shape = (28,)
      • 여기에 이미지 설명 입력
  • df.columns.size->28

이것은 나에게 효과가 있었다.

언급URL : https://stackoverflow.com/questions/20297332/how-do-i-retrieve-the-number-of-columns-in-a-pandas-data-frame

반응형